UVa12563劲歌金曲

题意:求在给定时间内,最多能唱多少歌曲,在最多歌曲的情况下,使唱的时间最长。
思路:01背包
把最后一秒留给《劲歌金曲》,算在 t-1 时间内最多能 完整 唱多少歌。因为题目里说了,一首歌要么不唱要么唱完(没看清,被坑了好久),所以初始化的时候就需要赋值为无穷小。但d[0] = 0;
其次,怎么求总时间?
得到最终的状态之后,从后往前枚举时间,找到歌最多的状态,记录这个时间和状态值。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = 1<<30;
const int N = 10000;
int d[N], v[55]; 
	
int main()
{
	//freopen("in.txt","r",stdin);
	int T,n,time; scanf("%d",&T);
	int kase = 1; 
	while(T--){
	
		scanf("%d %d",&n,&time);
		for(int i = 0; i < n; ++i) scanf("%d",&v[i]);
		
		// 这个初始化为无穷小,这样只可以加入那种能把整首唱完的。 
		for(int i = 1; i <= time; ++i) d[i] = -INF;
		d[0] = 0;
		--time;
		
		for(int i = 0; i < n; ++i){
			for(int j = time; j >= v[i]; --j){
				d[j] = max(d[j], d[j-v[i]] + 1);
			}
		}
		
		int num = -INF, pos;
		for(int i = time; i >= 0; --i){
			if(num < d[i]){
				num = d[i]; pos = i;
			}
		}
		
		printf("Case %d: %d %d\n",kase++,num+1,pos+678);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/CY05627/article/details/88356856