1. 程式人生 > >[Hackrank] Prime XOR (計數DP)

[Hackrank] Prime XOR (計數DP)

Hackrank - Prime XOR

給定N個數,求有多少個不同子集的異或和為質數
其中 N105,3500ai4500

首先異或和不會超過 2131
然後雖然 N 很大,但是每個數的範圍在1000以內
所以總的不同的數不會很多
所以做法是列舉每種數取了多少個,然後暴力轉移即可
剛開始我列舉的部分用的是組合數,但這是不對的
因為他要求不同子集,所以只要個數一定就不管他是從哪個位置取的
所以只要統計出每種數取奇數個的取法和取偶數個的取法轉移即可

#pragma comment(linker, "/STACK:102400000,102400000")
#include <cstdio>
#include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <cctype> #include <map> #include <set> #include <queue> #include <bitset> #include <string> #include <cassert> #include <complex>
using namespace std; typedef pair<int,int> Pii; typedef long long LL; typedef unsigned long long ULL; typedef double DBL; typedef long double LDBL; #define MST(a,b) memset(a,b,sizeof(a)) #define CLR(a) MST(a,0) #define SQR(a) ((a)*(a)) #define PCUT puts("\n----------") #define PRI(x) cout << #x << ": " << (x) << endl
#define PPR(x,y) cout << #x << " " << #y << ": " << (x) << " " << (y) << endl const int maxn=1e5+5, maxi=4500+5, MOD=1e9+7, maxv=1<<13; int N; int in[maxi]; LL dp[2][maxv]; bool sieve[maxv]; int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); #endif for(int i=2; i<maxv; i++) if(!sieve[i]) for(int j=i*i; j<maxv; j+=i) sieve[j]=1; int T; scanf("%d", &T); for(int ck=1; ck<=T; ck++) { scanf("%d", &N); CLR(in); for(int i=1,x; i<=N; i++) { scanf("%d", &x); in[x]++; } CLR(dp); int now=0,las=1; dp[now][0] = 1; for(int i=3500; i<=4500; i++) if(in[i]) { now^=1; las^=1; CLR(dp[now]); for(int j=0; j<maxv; j++) { dp[now][j] = ( dp[now][j] + (in[i]/2+1)*dp[las][j]%MOD)%MOD; dp[now][j^i] = ( dp[now][j^i] + ((in[i]-1)/2+1)*dp[las][j]%MOD)%MOD; } } LL ans=0; for(int i=2; i<maxv; i++) if(!sieve[i] && dp[now][i]) { ans = (ans+dp[now][i])%MOD; // if(dp[now][i]) printf("%d %lld\n", i, dp[now][i]); } printf("%lld\n", ans); } return 0; }