uva 624 - CD

题目:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=8&page=show_problem&problem=565

思路:裸的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;
}
View Code

 

posted @ 2013-07-28 00:03  over_flow  阅读(129)  评论(0编辑  收藏  举报