uva 624 - CD
思路:裸的01背包,输出路径,用一维数组标记的
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> #include <stack> using namespace std; int minute[25]; int dp[10010]; int cnt[10010]; int main() { int n,m; stack<int>s; while(scanf("%d%d",&m,&n)!=EOF) { while(!s.empty()) s.pop(); for(int i=1;i<=n;i++) scanf("%d",&minute[i]); memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) for(int j=m;j>=minute[i];j--) { if(dp[j]<dp[j-minute[i]]+minute[i]) { dp[j]=dp[j-minute[i]]+minute[i]; cnt[j]=i; } } int ans=dp[m],aans=dp[m]; while(ans>0) { s.push(cnt[ans]); ans-=minute[cnt[ans]]; } while(!s.empty()) { printf("%d ",minute[s.top()]); s.pop(); } printf("sum:%d\n",aans); } return 0; }