1. 程式人生 > >動態規劃——Happy Matt Friends

動態規劃——Happy Matt Friends

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. InputThe 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 ≤ 10 6
). 

In the second line, there are N integers ki (0 ≤ k i ≤ 10 6), indicating the i-th friend’s magic number. OutputFor 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個數,任選若干個數,使其異或和不小於m,求有多少種選法。

思路:

由於異或有這樣的性質:a^b^b=a,故設定dp[i][j]為從前i個數中選若干個數的異或和為j。

則有dp[i][j]=dp[i-1][j]+dp[i-1][j^a[i]]

同時根據題目資料1e6,可知異或和的最大值是1<<20-1。這個值不能大也不能小,否則會出錯。

dp陣列我用滾動陣列優化了下,不用滾動陣列應該也可以。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn=(1<<20);
ll dp[45][maxn];
int a[45];
int n, m;
int main()
{
    int t;
    scanf("%d", &t);
    for(int cas=1; cas<=t; cas++)
    {
        scanf("%d%d", &n, &m);
        for(int i=1; i<=n; i++)
            scanf("%d", &a[i]);
        memset(dp, 0, sizeof(dp));
        dp[0][0]=1;
        int pos=1;
        for(int i=1; i<=n; i++)
        {
            for(int j=0; j<maxn; j++)
                dp[pos][j]=dp[pos^1][j]+dp[pos^1][j^a[i]];
            pos^=1;
        }
        ll ans=0;
        for(int i=m; i<maxn; i++)
            ans+=dp[pos^1][i];
        printf("Case #%d: %lld\n", cas, ans);
    }
    return 0;
}