| 幂集 | ||||||
| ||||||
| Description | ||||||
| 所谓幂集,就是原集合中所有子集构成的集合,例如集合{1,2,3}的幂集为{{1},{2},{3},{1,2},{1,3},{2,3},{1,2,3},{空集}}。现有一个元素个数为n的集合A={a1,a2,a3,a4......an},请求出集合A的幂集中有多少个 子集的和等于整数x。 | ||||||
| Input | ||||||
|
有多组测试数据处理到文件结束,每组数据第一行包含两个整数n(n<=30)和x(x>0); 第二行有n个整数,0<ai<300,代表集合A中的元素。 | ||||||
| Output | ||||||
| 输出集合A的幂集中子集和为x的子集的个数。 | ||||||
| Sample Input | ||||||
|
5 6
1 2 2 4 5
3 7
1 2 3
| ||||||
| Sample Output | ||||||
|
3
0
| ||||||
| Hint | ||||||
|
第一组样例中{1,5},{2,4},{2,4}这三个子集的和都等于6,所以答案为3. | ||||||
| Source | ||||||
| 2014 Winter Holiday Contest 3 |
不知为啥,用Java做一直不对,用c++做就过了。
题解:这题涉及动态规划的背包
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <vector>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
//*************************
///o(っ。Д。)っ AC万岁!!!
//*************************
const int maxn = 70;
int arr[maxn] = {}, dp[94790] = {};
bool cmp(int a, int b);
int main()
{
int n, x;
while(cin >> n >> x)
{
mem(dp, 0);
for(int i = 1; i <= n; i++)
{
cin >> arr[i];
}
sort(arr + 1, arr + n + 1, cmp);
int sum = 0, ans = 0;
for(int i = 1; i <= n; i++)
{
sum += arr[i];
ans = i;
if(arr[i] >= x)
{
break;
}
}
for(int i = 1; i <= ans; i++)
{
for(int j = sum; j >= 0; j--)
{
if(dp[j] > 0) dp[j + arr[i]] += dp[j];
if(j == arr[i]) dp[j]++;
}
}
cout << dp[x] << endl;
}
return 0;
}
bool cmp(int a, int b)
{
return a < b;
}
/*
6 8
1 3 4 4 4 7
*/
本文介绍了一种使用动态规划解决特定幂集问题的方法,该问题要求计算集合中元素和等于给定值x的子集数量。通过分析输入数据特征并对元素进行排序,采用递推方式更新状态数组来实现高效求解。


2215

被折叠的 条评论
为什么被折叠?



