其他分享
首页 > 其他分享> > 子集问题

子集问题

作者:互联网

枚举 \([0,2^n-1]\) 子集 \(O(n^3)\)

for (int s = 0; s < 1 << n; s++)
	for (int ns = s; s; ns = (ns - 1) & s)

证明:

法1:

对于每一位

1. s = 0, ns = 0
2. s = 1, ns = 0, 1

每一位有 3 种情况,所以共有 \(3^n\) 个子集

法2:

二项式定理

\(C_n^k*2^k=(2+1)^n\)

子集和问题

高维前缀和

3维为例

for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
        for (int k = 1; k <= n; k++)
            f[i][j][k] += f[i-1][j][k];
for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
        for (int k = 1; k <= n; k++)
            f[i][j][k] += f[i][j-1][k];
for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++)
        for (int k = 1; k <= n; k++)
            f[i][j][k] += f[i][j][k-1];

子集和 - 题目 - Daimayuan Online Judge

求子集和,可视为 n 维前缀和,每一维只有 0,1 两个状态,因此可用一个整数来表示

for (int i = 0; i < n; i++)
	for (int j = 0; j < 1 << n; j++)
		if (j >> i & 1)
			f[j] += f[j - (1 << i)];
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>

using namespace std;
#define endl "\n"

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N  = (1 << 22) + 10;

unsigned int A,B,C;
inline unsigned int rng61() {
    A ^= A << 16;
    A ^= A >> 5;
    A ^= A << 1;
    unsigned int t = A;
    A = B;
    B = C;
    C ^= t ^ A;
    return C;
}

int n;
ll f[N];
int main(){
    scanf("%d%u%u%u", &n, &A, &B, &C);
    for (int i = 0; i < (1 << n); i++)
        f[i] = rng61();
    for (int i = 0; i < n; i++)
    	for (int j = 0; j < 1 << n; j++)
    		if (j >> i & 1)
    			f[j] += f[j - (1 << i)];
    ull ans = 0;
    for (int i = 0; i < 1 << n; i++)
    	ans ^= f[i];
    cout << ans << endl;
    return 0;
}

标签:typedef,ns,int,long,问题,子集,include
来源: https://www.cnblogs.com/hzy717zsy/p/16541451.html