HDU 5119 Happy Matt Friends (14北京 类背包dp)

本文探讨了一种通过计算特定组合的异或和来决定获胜条件的游戏策略。具体而言,Matt和他的朋友们玩一个游戏,通过选择一些朋友的魔法数字进行异或运算,如果结果大于或等于预设值M,则Matt赢得游戏。文章详细介绍了使用动态规划解决此问题的方法,并给出了解决方案的代码实现。


Happy Matt Friends

Time Limit: 6000/6000 MS (Java/Others)    Memory Limit: 510000/510000 K (Java/Others)

Total Submission(s): 667    Accepted Submission(s): 253

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.
 
Source
2014ACM/ICPC亚洲区北京站-重现赛(感谢北师和上交)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5119

题目大意:n个数,从中挑k个,使得这k个数的异或和不小于m,问有多少种挑选方法

题目分析:dp[i][j]表示前 i 个数中选择一些使得异或和为j的方法数,转移方程:dp[i][j] = dp[i - 1][j] + dp[i - 1][j ^ a[i]],即等于前i-1个异或和为j的方法数加上前i-1个异或和为j ^ a[i]的方法数,因为j ^ a[i] ^ a[i] == j ^ (a[i] ^ a[i]) == j ^ 0 = j,最后再累计一下j大于等于m时的方法数,这题内存给的够大,也可以直接采用滚动数组


#include <cstdio>
#include <algorithm>
#define ll long long
using namespace std;
int const MAX = (1 << 20);
ll dp[45][MAX];
int a[45];

int main()
{
    int T, n, m;
    scanf("%d", &T);
    for(int ca = 1; ca <= T; ca++)
    {
        memset(dp, 0, sizeof(dp));
        dp[0][0] = 1;
        scanf("%d %d", &n, &m);
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        for(int i = 1; i <= n; i++)
            for(int j = 0; j < MAX; j++)
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j ^ a[i]];
        ll ans = 0;
        for(int i = m; i < MAX; i++)
            ans += dp[n][i];
        printf("Case #%d: %I64d\n", ca, ans);
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值