題目連結: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;
}