一. Vjudge链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=34887
二. 题目大意:取KTV唱歌,每一首歌有不同的时间,总时间是有限的,最后还能唱一首时长为678s的歌,保证678s是最长的,歌没唱完不赶你走。求在最多能唱多少首歌,并且使得时间尽量长。歌的首数优先。
三.思路:01背包问题,总时间看成总的容量,每件物品价值为1,这是一个背包。保证这个背包优先的情况下,总时间看成总的容量,每件物品价值为物品体积,这是第二个背包,首先遵循第一个背包最优,然后如果有相同的情况,再保证第二个背包最优。
四.代码:
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
using namespace std;
const int MAX_N = 10010,
MAX_M = 15,
INF = 0x3f3f3f3f;
int dp[MAX_N], Time[MAX_N];
int main()
{
//freopen("in.txt", "r", stdin);
int test, num, maxWeight, i, j, weight, kase = 1;
scanf("%d", &test);
while(test--){
scanf("%d %d", &num, &maxWeight);
memset(dp, 0, sizeof(dp));
memset(Time, 0, sizeof(Time));
for(i = 0; i < num; i++){
scanf("%d", &weight);
for(j = maxWeight; j > weight; j--){
if(dp[j] < dp[j-weight] + 1){
dp[j] = dp[j-weight] + 1;
Time[j] = Time[j-weight] + weight;
}
else if(dp[j] == dp[j-weight] + 1)
Time[j] = max(Time[j], Time[j-weight] + weight);
}
}
printf("Case %d: %d %d\n", kase++, dp[maxWeight]+1, Time[maxWeight] + 678);
}
return 0;
}