UVa 12563 劲歌金曲(0-1背包)

https://vjudge.net/problem/UVA-12563

题意:

在一定的时间内连续唱歌,最后一首唱11分钟18秒的劲歌金曲,问最多能长多长时间。

思路:

0-1背包问题,背包容量为t-1,因为至少还要留1秒钟来放劲歌金曲。还需要注意的是题目要求的是在唱最多首歌的情况下所能唱的最长时间,所以这里我们来限制一下时间,对于j时刻,我们要求正好唱完这首歌,那么这样唱的歌肯定是最多的。

#include<iostream> 
#include<algorithm>
#include<cstring>
using namespace std;

const int maxn = 5000+5;
int a[maxn], d[maxn], t, n;

int main()
{
    int cas,kase=0;
    cin >> cas;
    while (cas--)
    {
        memset(d, -1, sizeof(d));
        d[0] = 0;
        cin >> n >> t;
        for (int i = 0; i < n; i++)
            cin >> a[i];
        for (int i = 0; i < n;i++)
        for (int j = t - 1; j >= a[i]; j--)
            d[j] = max(d[j], d[j - a[i]] + 1);
        int cnt = 0, sum;
        for (int i = 0; i < t; i++)
        {
            if (d[i] >= cnt)
            {
                cnt = d[i];
                sum = i;
            }
        }
        printf("Case %d: %d %d
", ++kase, cnt+1, sum + 678);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zyb993963526/p/6362180.html