首页 > 代码库 > hihocoder offer收割编程练习赛11 B 物品价值

hihocoder offer收割编程练习赛11 B 物品价值

思路:

状态压缩 + dp。

实现:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 const int INF = 0x3f3f3f3f;
 8 
 9 int t, n, m, s;
10 int V[1005], S[1005], dp[1005][(1 << 11) + 5];
11 
12 int dfs(int now, int s)
13 {
14     if (dp[now][s] != -1)
15         return dp[now][s];
16     if (now == n)
17     {
18         if (s == (1 << m) - 1)
19             return 0;
20         return -INF;
21     }
22     int x = dfs(now + 1, s ^ S[now]) + V[now];
23     int y = dfs(now + 1, s);
24     return dp[now][s] = max(x, y);
25 }
26 
27 int main()
28 {
29     cin >> t;
30     while (t--)
31     {
32         memset(dp, -1, sizeof(dp));
33         cin >> n >> m;
34         for (int i = 0; i < n; i++)
35         {
36             cin >> V[i] >> s;
37             int tmp = 0, total = 0;
38             for (int j = 0; j < s; j++)
39             {
40                 cin >> tmp;
41                 tmp--;
42                 total |= (1 << tmp);
43             }
44             S[i] = total;
45         }
46         cout << dfs(0, 0) << endl;
47     }
48     return 0;
49 }

 

hihocoder offer收割编程练习赛11 B 物品价值