# 2044 problem C magic pocket

Posted by iankent on Sun, 03 May 2020 07:47:23 +0200

Question C: Magic pocket
Time limit: 1 Sec memory limit: 32 MB
Flower offering: 102 solution: 56
[flower offering] [wreath] [TK question bank]
Title Description

There is a magic pocket with a total volume of 40. You can use this pocket to make some items. The total volume of these items must be 40. John now has n items he wants to get. The volume of each item is a1, a2 An. John can choose some of these items. If the total volume of the selected items is 40, John can get these items by using this magic pocket. The question now is how many different ways John can choose an item.

input

The first line of input is a positive integer n (1 < = n < = 20), indicating the number of different items. Next N lines, each line has a positive integer between 1 and 40, giving a1, a2 The value of an.

output

Output the number of different ways to choose items.

sample input
2
12
28
3
21
10
5
sample output
1
0

• Implementation with depth traversal
```#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: Immortals
Time:2 ms
Memory:1704 kb
****************************************************************/```
• Normal recursion
```#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); //Either join or not join for the nth
}

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: Immortals
Time:2 ms
Memory:1704 kb
****************************************************************/```