HDU 5119 Happy Matt Friends (背包DP + 滚动数组)
题目链接:HDU 5119
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 \le N \le 40, 0 \le M \le 10^6)\).
In the second line, there are \(N\) integers \(k_i (0 ≤ k_i ≤ 10^6)\), 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亚洲区北京站-重现赛(感谢北师和上交)
Solution
题意
给定 \(n\) 个数 \(k[i]\),从中取出一些数使得异或和大于等于 \(m\),求有几种取法。
思路
背包DP 滚动数组
设 \(dp[i][j]\) 表示前 \(i\) 个数中异或和为 \(j\) 的所有取法。状态转移方程为 \(dp[i][j] = dp[i - 1][j] + dp[i - 1][j\ xor\ k[i]]\)。
由于当前状态只和前一个状态有关,因此可以用滚动数组优化。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1 << 20;
ll dp[10][maxn];
ll k[50];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
for(int _ = 1; _ <= T; ++_) {
memset(dp, 0, sizeof(dp));
dp[0][0] = 1;
int n, m;
cin >> n >> m;
for(int i = 1; i <= n; ++i) {
cin >> k[i];
}
for(int i = 1; i <= n; ++i) {
for(int j = 0; j < maxn; ++j) {
dp[i & 1][j] = dp[(i - 1) & 1][j] + dp[(i - 1) & 1][j ^ k[i]];
}
}
ll ans = 0;
for(int i = m; i < maxn; ++i) {
ans += dp[n & 1][i];
}
cout << "Case #" << _ << ": " << ans << endl;
}
return 0;
}
最新文章
- AES加密时的 java.security.InvalidKeyException: Illegal key size 异常
- iOS 验证邮箱手机号格式
- Excel REPT函数使用
- 使用OC开发phonegp 组件
- Java中String、StringBuilder以及StringBuffer
- TI C66x DSP 系统events及其应用 - 5.8(ISTP)
- 排序算法门外汉理解-Shell排序
- thoughtworks笔试整理
- 五大科技巨头VR/AR专利报告,Magic Leap以22.6%领跑
- [转载]Reids配置文件详解
- AsyncTask源码笔记
- wxPython的简单应用
- [2019BUAA软工助教]Alpha阶段无人转出申请审核结果
- 信息摘要算法之六:HKDF算法分析与实现
- Codeforces 1139D Steps to One dp
- java.lang.OutOfMemoryError及解决方案
- length() 用法
- 混合开发 Hybird Ionic Angular Cordova web 跨平台 MD
- mysql快速移植表数据
- SQL Server中的事务与其隔离级别之脏读, 未提交读,不可重复读和幻读