hdu 5188(带限制的01背包)

zhx and contest

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 757    Accepted Submission(s): 282


Problem Description
As one of the most powerful brushes in the world, zhx usually takes part in all kinds of contests.
One day, zhx takes part in an contest. He found the contest very easy for him.
There are n problems in the contest. He knows that he can solve the ith problem in ti units of time and he can get vi points.
As he is too powerful, the administrator is watching him. If he finishes the ith problem before time li, he will be considered to cheat.
zhx doesn't really want to solve all these boring problems. He only wants to get no less than w points. You are supposed to tell him the minimal time he needs to spend while not being considered to cheat, or he is not able to get enough points.
Note that zhx can solve only one problem at the same time. And if he starts, he would keep working on it until it is solved. And then he submits his code in no time.
 
Input
Multiply test cases(less than 50). Seek EOF as the end of the file.
For each test, there are two integers n and w separated by a space. (1n30, 0w109)
Then come n lines which contain three integers ti,vi,li. (1ti,li105,1vi109)
 
Output
For each test case, output a single line indicating the answer. If zhx is able to get enough points, output the minimal time it takes. Otherwise, output a single line saying "zhx is naive!" (Do not output quotation marks).
 
Sample Input
1 3 1 4 7 3 6 4 1 8 6 8 10 1 5 2 2 7 10 4 1 10 2 3
 
Sample Output
7 8 zhx is naive!
 
Source
 
 
题意:zhx要完成 n 道题目,完成第i道题目所需时间为 ti ,它必须在不小于 li 的时间内完成,获得的分数是 vi,现在要求zhx获得 w 分,问他最少需要多少时间来获得 w 分?
题解:如果没有 li 的限制就是一道 01 背包。。加了限制就变成难题了。。。我们应该按照开始时间 l - t 进行排序,为什么?l-t是开始时间 ,我们假设start1 < start2 ,那么从1开始做这件两件事情是要小于从2开始做这两件事情的。所以排完序之后再做01背包得到最少的时间。
#include<iostream>
#include<cstdio>
#include<cstring>
#include <algorithm>
#include <math.h>
using namespace std;
typedef long long LL;
const int N = 3000005;
struct Node{
    int t,v,l;
}node[35];
int dp[N];
int n,w;
int cmp(Node a,Node b){
    if(a.l-a.t==b.l-b.t) return a.l<b.l;  ///按照开始时间进行排序
    return a.l-a.t<b.l-b.t;
}
int main()
{
    while(scanf("%d%d",&n,&w)!=EOF){
        int s = 0;
        for(int i=1;i<=n;i++){
            scanf("%d%d%d",&node[i].t,&node[i].v,&node[i].l);
            s+=max(node[i].l,node[i].t);
        }
        sort(node+1,node+1+n,cmp);
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++){
            int start = max(node[i].l,node[i].t);
            for(int j=s;j>=start;j--){
                dp[j] = max(dp[j],dp[j-node[i].t]+node[i].v);
            }
        }
        int ans = s+1;
        for(int i=0;i<=s;i++){
            if(dp[i]>=w){
                ans = i;
                break;
            }
        }
        if(ans!=s+1) printf("%d
",ans);
        else printf("zhx is naive!
");
    }
    return 0;
}
原文地址:https://www.cnblogs.com/liyinggang/p/5701025.html