ZOJ-3707 Happy Programming Contest(01背包)

题意

T 的时间, n 道题,每道题都有所需的时间和价值,现在需要一种方案使得总价值最大,相同的情况取总题数多的,题数也相同的情况取罚时少的。

思路

把时间看做费用,题的价值看成物品的价值,就是一个01背包,只不过对“更好情况”的判定不是单纯的比大小,把状态定义成结构体即可。

代码

#include<iostream>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<vector>
#define FOR(i,x,y) for(int i=(x);i<=(y);i++)
#define DOR(i,x,y) for(int i=(x);i>=(y);i--)
typedef long long LL;
using namespace std;

struct Prob
{
    int t,v;
    bool operator <(const Prob &_)const
    {
        return t<_.t;
    }
}a[53];

struct node
{
    int v,p,t;
    bool operator <(const node &_)const
    {
        if(v!=_.v)return v<_.v;
        if(p!=_.p)return p<_.p;
        if(t!=_.t)return t>_.t;
        return 0;
    }
    void update(node _)
    {
        if((*this)<_)
            (*this)=_;
        return;
    }
    void Print(){printf("%d %d %d\n",v,p,t);}
};

int main()
{
    int TOT;
    scanf("%d",&TOT);
    while(TOT--)
    {
        int T,n;
        node dp[1003],ans;
        memset(dp,0,sizeof(dp));ans.p=ans.v=ans.t=0;
        scanf("%d%d",&T,&n);
        FOR(i,1,n)scanf("%d",&a[i].t);
        FOR(i,1,n)scanf("%d",&a[i].v);
        sort(a+1,a+1+n);
        FOR(i,1,n)
            DOR(j,T,a[i].t)
            {
                dp[j].update((node){dp[j-a[i].t].v+a[i].v,dp[j-a[i].t].p+1,dp[j-a[i].t].t+j});
                ans.update(dp[j]);
            }
        ans.Print();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/paulliant/article/details/80814499