4120: coins (dynamic programming)

 

Total time limit: 
1000ms
 
Memory Limit: 
262144kB
description

Astronaut Bob arrived on Mars one day, he has a habit of collecting coins. He will face value of all the coins on Mars were collected, and a total of n species each have only one: in denominations of A 1 , A 2 ... A n. Bob at the airport saw a favorite gift to buy for a friend Alice, this gift is the price of X dollars. Bob would like to know in order to buy his gift which coins are to be used, that Bob must give up what kind of coin collecting good. Airport does not provide give change only accept just X dollars.

Entry
The first line contains two positive integers n and x. (1 <= n <= 200 , 1 <= x <= 10000)
of the second row to greatly small positive integer n a1, a2, a3 ... an ( 1 <= ai <= x)
Export
The first line is an integer that is how many coins are to be used.
The second line is the coin denomination that must be used (in ascending order).
Sample input
5 18
1 2 3 5 10
Sample Output
2
5 10
prompt
The input data is guaranteed a given coin denomination at least one combination can just to pay $ X.
Must be used if the coin does not exist, then the first line of output 0, output line of the second blank line.

Problem-solving ideas: We consider a [i] actually meets the essential element easy to think, f [x] -f [xa [i]] is zero, but the number of schemes f [xa [i]] is also possible use a [i], so f [xa [i]] - f [xa [i] * 2], is to sort out the f [x] -f [xa [ i]] + f [xa [i] * 2 ], is also very easy to find the inclusion-exclusion law, thereby solving recursive, recursive boundary xa [i] * k <0 or f [xa [i] * k ] == 0;
time complexity of algorithm
----- -----------
original link: https: //blog.csdn.net/qq_18455665/article/details/50285203

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 using namespace std;
 5 #define N 205
 6 #define M 10005
 7 int n,x,l;
 8 int a[N],ans[N];
 9 int f[M];
10 int calc(int x,int v) {
11     if(x<0) return 0;
12     else return f[x]-calc(x-v,v);
13 }
14 int main() {
15     scanf("%d%d",&n,&x);
16     for(int i=1; i<=n; i++) scanf("%d",&a[i]);
17     f[0]=1;
18     for(int i=1; i<=n; i++)
19         for(int j=x; j>=a[i]; j--)
20             f[j]+=f[j-a[i]];
21     for(int i=1; i<=n; i++) {
22         if(!(f[x]-calc(x-a[i],a[i]))) {
23             ans[++l]=a[i];
24         }
25     }
26     printf("%d\n",l);
27     for(int i=1; i<=l; i++) printf("%d ",ans[i]);
28     return 0;
29 }

 

Guess you like

Origin www.cnblogs.com/aiqinger/p/12607757.html