Dairy Queen

v cows Bassie go DQ work, met a guest gave a good large denomination bills, so Bassie had to in order to give the customer the change and face the question: now store a total of n kinds of coins, these different kinds of coins numbered, to coin denomination i is c [i]. Because the finger cows is limited, so he can only help you to it. (Known as the total number of the change required total) (1 <= total < = 1000,1 <= n <= 1000,1 <= c [i] <= 300) v solution seeking a total number of species? v [Enter] v The first line of coins worth total number and types of coins n. The following v n values behavior C [I], I = l, 2,3 ... NV [output] v row, the number of programs solution

Sol: ask this question several programs, recursive, complete knapsack problem. Provided ANS [i] [j] denotes the i prior to use of coins consisting of a number of program j dollars. For the i type of coins, two options not useful and, if not, ANS [i] [j] equal ANS [i-1] [j] (i.e., i-1 equal to the previous number of constituent program type of coins dollars j) , if, ans [i] [j] equal ans [i] [jc [i]] (i.e., i is equal to the former type of coin JC composition [i] is the number of dollars scheme. Note that this is ans [i] [jc [ i]], instead ans [i-1] [jc [i]], because the backpack is infinite). Whereby recursive formula: ans [i] [j] = ans [i-1] [j] + ans [i] [jc [i]]. Border: ans [i] [0] = 1,0 <= i <= n, i.e. before the i number of coins constituting one embodiment of dollars 0.

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int  c[1005];
 4 long long ans[1005][1005];
 5 int main()
 6 {
 7     int n,total;
 8     cin>>n>>total;
 9     ans[0][0]=1;
10     for (int i=1;i<=n;i++)
11     {
12          CIN >> C [I];
 13 is           ANS [I] [ 0 ] = . 1 ;
 14      }
 15      for ( int I = . 1 ; I <= n-; I ++ )
 16        for ( int J = . 1 ; J <= Total; J ++ )
 . 17        {
 18 is            ANS [I] [J] = ANS [I- . 1 ] [J] + ANS [I] [JC [I]];
 . 19          // note after the plus sign ans [i] [jc [ I]], the infinite because the backpack, allowing repeated several times with 
20 is        }
 21 is      COUT << ANS [n-] [Total] << endl;
 22 is      return  0 ;     
23 } 

 

One-dimensional writing:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int  c[1005];
 4 long long ans[1005];
 5 int main()
 6 {
 7     int n,total;
 8     cin>>n>>total;
 9     ans[0]=1;
10     for (int i=1;i<=n;i++)
11          cin>>c[i];
12     for (int i=1;i<=n;i++)
13       for (int j=0;j<=total;j++)
14             if (j-c[i]>=0) 
15             ans[j]+=ans[j-c[i]];
16     cout<<ans[total]<<endl;
17     return 0;     
18 } 

Guess you like

Origin www.cnblogs.com/cutepota/p/12129695.html