TZOJ 5962 Happy Matt Friends(计数DP)

描述

Matt hzs 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.

输入

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.

输出

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.

样例输入

2
3 2
1 2 3
3 3
1 2 3

样例输出

Case #1: 4
Case #2: 2

提示

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个数选择任意个数求异或和大于M的方案数。

题解

计数DP。

dp[i][j]代表第i个物品异或和为j的方案数。

显然dp[i][j]=dp[i-1][j]+dp[i-1][j^a[i]](不装i或者装i)。

由于j高达1e6,所以需要滚动一维i。

代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 #define LL long long
 5 LL dp[2][1<<20];
 6 int main()
 7 {
 8     ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
 9     int t,n,m,ca=1,a[45];
10     cin>>t;
11     while(t--)
12     {
13         cin>>n>>m;
14         int mx=0;
15         for(int i=1;i<=n;i++)cin>>a[i],mx=max(mx,a[i]);
16         int sta=1;
17         while(sta<=mx)sta<<=1;
18         for(int i=0;i<sta;i++)dp[0][i]=dp[1][i]=0;
19         dp[0][0]=1;
20         int cur=1;
21         for(int i=1;i<=n;i++,cur^=1)
22         {
23             for(int j=0;j<sta;j++)
24                 dp[cur][j]=dp[cur^1][j]+dp[cur^1][j^a[i]];
25             for(int j=0;j<sta;j++)
26                 dp[cur^1][j]=0;
27         }
28         LL sum=0;
29         for(int i=m;i<sta;i++)sum+=dp[cur^1][i];
30         cout<<"Case #"<<ca++<<": "<<sum<<endl;
31     }
32     return 0;
33 }

posted on 2019-10-31 13:55  大桃桃  阅读(168)  评论(0编辑  收藏  举报

导航