或与异或 [背包dp]

或与异或

给出一个序列 a1,a2,a3...ana_1, a_2, a_3...a_n, 求 选取任意个数使得其 异或起来的值 等于 或起来的值 的⽅案数 .

n50,ai213n le 50, a_i le 2^{13}


color{red}{正解部分}

考虑 O(213)O(2^{13}) 枚举最后的答案 xx,

现在要选出一些数字, 使得它们的 异或和 等于 或和 等于 xx,

  • 对于要求: 或和 等于 xx, 则选出的数字必须要在二进制下作为 xx 的子集, 于是可以通过枚举子集预处理出预选数, 共有 tottot 个 .
  • 对于要求: 异或和 等于 xx, 可以对预选数做 背包 求出, 具体来说, 设 F[i,j]F[i, j] 表示前 ii 个数字, 异或和jj 的方案数, 最后 F[tot,j]F[tot, j] 即为对答案的贡献 .

下有优化 .


color{red}{实现部分}

注意 异或背包 不能压缩数组维度,

朴素实现如下 downarrow

#include<bits/stdc++.h>
#define reg register
typedef long long ll;

int read(){
        char c;
        int s = 0, flag = 1;
        while((c=getchar()) && !isdigit(c))
                if(c == '-'){ flag = -1, c = getchar(); break ; }
        while(isdigit(c)) s = s*10 + c-'0', c = getchar();
        return s * flag;
}

const int maxn = 55;

int N;
int M;
int A[maxn];
int B[maxn];

ll Ans;
ll F[maxn][20004];

int main(){
        N = read();
        for(reg int i = 1; i <= N; i ++) A[i] = read();
        for(reg int x = 1; x <= (1<<14)-1; x ++){
                int tot = 0;
                for(reg int i = 1; i <= N; i ++)
                        if((A[i] | x) == x) B[++ tot] = A[i];
                F[0][0] = 1;
                for(reg int i = 1; i <= tot; i ++)
                        for(reg int j = x; j >= 0; j --) F[i][j] = F[i-1][j] + F[i-1][j^B[i]];
                Ans += F[tot][x];
        }
        printf("%lld
", Ans);
        return 0;
}

用时 720ms720ms .

从背包容量着手继续优化, 发现背包的容量为 xx 的 二进制子集时才有意义, 于是将所有有意义的背包容量预处理, 在进行背包, 具体见代码注释处,

#include<bits/stdc++.h>
#define reg register
typedef long long ll;

int read(){
        char c;
        int s = 0, flag = 1;
        while((c=getchar()) && !isdigit(c))
                if(c == '-'){ flag = -1, c = getchar(); break ; }
        while(isdigit(c)) s = s*10 + c-'0', c = getchar();
        return s * flag;
}

const int maxn = 55;

int N;
int M;
int A[maxn];
int B[maxn];
int C[20004];

ll Ans;
ll F[maxn][20004];

int main(){
        N = read();
        for(reg int i = 1; i <= N; i ++) A[i] = read();
        for(reg int x = 1; x <= (1<<14)-1; x ++){
                int tot = 0, cnt = 0;
                for(reg int i = x; i; i = (i-1)&x) C[++ cnt] = i;
                C[++ cnt] = 0;
                for(reg int i = 1; i <= N; i ++)
                        if((A[i] | x) == x) B[++ tot] = A[i];
                F[0][0] = 1;
                for(reg int i = 1; i <= tot; i ++)
                        for(reg int j = cnt; j >= 1; j --) F[i][C[j]] = F[i-1][C[j]] + F[i-1][C[j]^B[i]];
                Ans += F[tot][x];
        }
        printf("%lld
", Ans);
        return 0;
}

用时 68ms68ms .

原文地址:https://www.cnblogs.com/zbr162/p/11822407.html