Happy Matt Friends(dp)

时间:2022-11-27 20:59:13

Happy Matt Friends

Time Limit: 6000/6000 MS (Java/Others)    Memory Limit: 510000/510000 K (Java/Others)
Total Submission(s): 1810    Accepted Submission(s): 715

Problem Description
Matt has N friends. They are playing a game together.

Each of Matt’s friends has a magic number. In the game, Matt selects
some (could be zero) of his friends. If the xor (exclusive-or) sum of
the selected friends’magic numbers is no less than M , Matt wins.

Matt wants to know the number of ways to win.

 
Input
The first line contains only one integer T , which indicates the number of test cases.

For each test case, the first line contains two integers N, M (1 ≤ N ≤ 40, 0 ≤ M ≤ 106).

In the second line, there are N integers ki (0 ≤ ki ≤ 106), indicating the i-th friend’s magic number.

 
Output
For each test case, output a single line “Case #x: y”, where x is the
case number (starting from 1) and y indicates the number of ways where
Matt can win.
 
Sample Input
2
3 2
1 2 3
3 3
1 2 3
 
Sample Output
Case #1: 4
Case #2: 2
Hint

In the first sample, Matt can win by selecting:
friend with number 1 and friend with number 2. The xor sum is 3.
friend with number 1 and friend with number 3. The xor sum is 2.
friend with number 2. The xor sum is 2.
friend with number 3. The xor sum is 3. Hence, the answer is 4.

 题解:N范围为40,权值范围为10^6 约等于2的20次方,可以考虑类似dp+位运算的做法。因为异或值一定不会大于2^20,
所以可以枚举这个值,所以可以列出方程f[i][j]=f[i][j]+f[i][j^a[i]];
另外我用暴力也写了一发,虽然知道10000%超时;
dp代码:
 #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=<<;
int dp[][MAXN<<];//刚开始开到MAXN+10 RE,改成这才对;
int main(){
int T,N,M,flot=;
int m[];
scanf("%d",&T);
while(T--){
scanf("%d%d",&N,&M);
memset(dp,,sizeof(dp));
dp[][]=;
int x=;
for(int i=;i<N;i++){
x^=;
scanf("%d",m+i);
for(int j=;j<=MAXN;j++){
dp[x][j]=dp[x^][j]+dp[x^][j^m[i]];
//代表上一次值为j^m[i]现在再^m[i]等于j了再加上上次j的个数;
}
}
long long ans=;
for(int i=M;i<=MAXN;i++)ans+=dp[x][i];
printf("Case #%d: %lld\n",++flot,ans);
}
return ;
}

暴力超时:

 #include<stdio.h>
int ans,dt[];
int N,M;
void dfs(int top,int sox,int num,int t){
if(num==t){
if(sox>=M)ans++;
return;
}
for(int i=top;i<N;i++){
dfs(i+,sox^dt[i],num+,t);
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d",&N,&M);
for(int i=;i<N;i++)scanf("%d",dt+i);
ans=;
for(int i=;i<=N;i++){
dfs(,,,i);
}
printf("%d\n",ans);
}
return ;
}