您的位置:首页 > 其它

uva12563(01背包变形,多条件最优解)

2018-03-20 00:01 423 查看
题意:题意:n首歌,每首歌有其长度,还剩t秒,不包括678秒的《劲歌金曲》

输出唱的总曲目和时间总长度

思路:对于这种求多条件最优解的问题,推荐使用结构体,可以在结构体内重载小于号,也可以自己定义一个max(关于所使用的结构体),模拟01背包中的max。

对于这题而言需要注意以下几点:一是要注意题目的最优解必定是在t时间的最后一秒再唱劲霸金曲(即+678),其二如果不像博主上面说的一样使用结构体,那么是需要令定义一个数组来标记唱歌所花的时间的,因为在dp的过程中是只存储最大歌唱数目,并没有记录时间。

ac代码(注释掉的语句是另一种写法)

#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <map>
#include <set>
#include <vector>
#include <queue>
#define inf 0x3f3f3f3f
#define eps 1e-8
#define pi 3.1415
typedef long long ll;
using namespace std;
struct node
{
int num;
int Time;
//    bool x`operator <(const node &a)const
//    {
//        return num<a.num||(num==a.num&&Time<a.Time);
//    }
} dp[9005];//采取逆序滚动数组,所以只有一维
int n,t,p,tt[55];
node max(node a,node b)//自定义max函数
{
if(a.num>b.num) return a;
else if(a.num==b.num&&a.Time>b.Time)return a;
else return b;
}
int main()
{
scanf("%d",&p);
for(int k=1; k<=p; k++)
{
memset(dp,0,sizeof(dp));
int ans=0;
scanf("%d%d",&n,&t);
for(int i=1; i<=n; i++)
{
scanf("%d",&tt[i]);
ans+=tt[i];
}
t=min(t-1,ans);//对dp的时间t进行确定
for(int i=1; i<=n; i++)
{
for(int j=t; j>=tt[i]; j--)
{
node tmp;//记录结构体数据
tmp.num=dp[j-tt[i]].num+1;
tmp.Time=dp[j-tt[i]].Time+tt[i];
//                if(dp[j]<tmp)
//                {
//                    dp[j]=tmp;
//                }
dp[j]=max(dp[j],tmp);
}
}
printf("Case %d: %d %d\n",k,dp[t].num+1,dp[t].Time+678);//输出结果
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: