Advertisement
Imran2544

CD

Jan 6th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int N, ans;
  4. int songs[31];
  5. int dp[31][100];
  6. int mark[31][100];
  7.  
  8. int solve (int i, int now, int n)
  9. {
  10.     if (i==n)
  11.         return 0;
  12.     if (dp[i][now]!=-1) return dp[i][now];
  13.     int r1=0, r2=0;
  14.     if (now+songs[i]<=N)
  15.         r1=songs[i]+solve(i+1, now+songs[i], n);
  16.     r2=solve(i+1, now, n);
  17.     int mx;
  18.     if (r1>=r2) {
  19.         mx=r1;
  20.         mark[i][now]=1;
  21.     }
  22.     else {
  23.         mx=r2;
  24.         mark[i][now]=2;
  25.     }
  26.     return dp[i][now]=mx;
  27. }
  28.  
  29. void print (int i, int now)
  30. {
  31.     if (mark[i][now]==-1)
  32.         return;
  33.     if (mark[i][now]==1 && dp[i][now]<=ans) {
  34.         cout<<songs[i]<<" ";
  35.         print(i+1, now+songs[i]);
  36.     }
  37.     else if (mark[i][now]==2)
  38.         print(i+1, now);
  39. }
  40.  
  41. int main()
  42. {
  43.     int k;
  44.     while (cin>>N) {
  45.         cin>>k;
  46.         for (int i=0; i<k; i++) {
  47.             cin>>songs[i];
  48.         }
  49.         memset(dp, -1, sizeof dp);
  50.         memset(mark, -1, sizeof mark);
  51.         ans=solve(0, 0, k);
  52.         print(0, 0);
  53.         cout<<"sum:"<<ans<<endl;
  54.     }
  55.     return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement