问题 C: 神奇的口袋
时间限制: 1 Sec 内存限制: 32 MB
献花: 102 解决: 56
[献花][花圈][TK题库]
题目描述
有一个神奇的口袋,总的容积是40,用这个口袋可以变出一些物品,这些物品的总体积必须是40。John现在有n个想要得到的物品,每个物品的体积分别是a1,a2……an。John可以从这些物品中选择一些,如果选出的物体的总体积是40,那么利用这个神奇的口袋,John就可以得到这些物品。现在的问题是,John有多少种不同的选择物品的方式。
输入
输入的第一行是正整数n (1 <= n <= 20),表示不同的物品的数目。接下来的n行,每行有一个1到40之间的正整数,分别给出a1,a2……an的值。
输出
输出不同的选择物品的方式的数目。
样例输入
2
12
28
3
21
10
5
样例输出
1
0
- 用深度遍历实现
#include <iostream>
#include <fstream>
using namespace std;
const int MaxN = 40;
int ans = 0, P[MaxN] ,n ,wei;
void DFS(int P[],int k,int weight)
{
if (wei >= weight)
{
if (wei == weight)
++ans;
return;
}
for (int i = k; i < n; ++i)
{
wei += P[i];
DFS(P, i + 1, weight);
wei -= P[i];
}
}
int main()
{
#ifdef _DEBUG
ifstream cin("data.txt");
#endif // _DEBUG
while (cin >> n)
{
wei = ans = 0;
for (int i = 0; i < n; ++i)
cin >> P[i];
DFS(P,0,40);
printf("%d\n", ans);
}
#ifdef _DEBUG
cin.close();
#ifndef _CODEBLOCKS
system("pause");
#endif // !_CODEBLOCKS
#endif // _DEBUG
return 0;
}
/**************************************************************
Problem: 2044
User: Sharwen
Language: C++
Result: 升仙
Time:2 ms
Memory:1704 kb
****************************************************************/
- 普通递归
#include <iostream>
#include <fstream>
using namespace std;
const int MaxN = 40;
int ans = 0, P[MaxN] ,n ,wei;
int recursion(int sum, int n)
{
if (sum == 0)return 1;
if (n == 0)return 0;
return recursion(sum, n - 1) + recursion(sum - P[n-1], n - 1); //对第n个 要么加入,要么不加入
}
int main()
{
#ifdef _DEBUG
ifstream cin("data.txt");
#endif // _DEBUG
while (cin >> n)
{
wei = ans = 0;
for (int i = 0; i < n; ++i)
cin >> P[i];
printf("%d\n", recursion(40,n));
}
#ifdef _DEBUG
cin.close();
#ifndef _CODEBLOCKS
system("pause");
#endif // !_CODEBLOCKS
#endif // _DEBUG
return 0;
}
/**************************************************************
Problem: 2044
User: Sharwen
Language: C++
Result: 升仙
Time:2 ms
Memory:1704 kb
****************************************************************/