算法实验9:背包 (01背包)

题目链接:http://acm.sdibt.edu.cn/JudgeOnline/problem.php?id=4808

 

#include<iostream>
#include<map>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;

const int maxn=101;
int main()
{
    int t,n,ans,m,dp[10001],input[101];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&m);
        scanf("%d",&n);
        for (int i=1; i<=n; i++)
            scanf("%d",&input[i]);
        for (int i=1; i<=10000; i++)
            dp[i]=maxn;//需要的钱数初始化成最大数目

        dp[0]=0;////支付0元需要0张钱
        for (int i=1; i<=n; i++)
            for (int j=10000; j>=input[i]; j--)
                dp[j]=min(dp[j-input[i]]+1,dp[j]);
        for (int i=m; i<=10000; i++)
            if (dp[i]!=maxn)
            {
                ans=i;
                break;
            }
        printf("%d %d\n",ans,dp[ans]);
    }
    return 0;
}

 

posted on 2019-10-23 11:26  一只小毛球  阅读(491)  评论(0编辑  收藏  举报

导航