[BZOJ4589]Hard Nim
题意
求选出\(n\)个\([1,m]\)之间的质数使其异或和为\(0\)的方案数。
\(n\le10^9,m\le50000\)
sol
设\(f_{i,j}\)表示已经选了\(i\)个数异或和为\(j\)的方案数。
直接\(dp\)转移复杂度\(O(m^2n)\)
发现\(n\)次的转移是一样的可以快速幂优化\(O(m^2\log n)\)
再加个\(FWT\)就能做到\(O(m\log n)\)了。
code
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
int gi(){
int x=0,w=1;char ch=getchar();
while ((ch<'0'||ch>'9')&&ch!='-') ch=getchar();
if (ch=='-') w=0,ch=getchar();
while (ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return w?x:-x;
}
const int N = 1e5+5;
const int mod = 1e9+7;
int zhi[N],pri[N],tot,n,m,a[N],b[N];
void fwt(int *P,int len,int opt){
for (int i=1;i<len;i<<=1)
for (int p=i<<1,j=0;j<len;j+=p)
for (int k=0;k<i;++k)
{
int x=P[j+k],y=P[j+k+i];
P[j+k]=1ll*opt*(x+y)%mod;
P[j+k+i]=1ll*opt*(x-y+mod)%mod;
}
}
void mul(int *a,int *b,int len){
for (int i=0;i<len;++i)
a[i]=1ll*a[i]*b[i]%mod;
}
void fastpow(int *a,int *b,int n,int len){
fwt(a,len,1);fwt(b,len,1);
for (;n;mul(a,a,len),n>>=1) if (n&1) mul(b,a,len);
fwt(b,len,(mod+1)/2);
}
int main(){
zhi[1]=1;
for (int i=2;i<=N-5;++i){
if (!zhi[i]) pri[++tot]=i;
for (int j=1;j<=tot&&i*pri[j]<=N-5;++j){
zhi[i*pri[j]]=1;
if (i%pri[j]==0) break;
}
}
while (scanf("%d%d",&n,&m)!=EOF){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
int i,len;
for (i=1;pri[i]<=m;++i) ++a[pri[i]];
for (len=1;len<=pri[i-1];len<<=1) ;
b[0]=1;fastpow(a,b,n,len);
printf("%d\n",b[0]);
}
return 0;
}