pat-top 1002 Business(01背包)

4 篇文章 0 订阅

1002 Business (35 分)

As the manager of your company, you have to carefully consider, for each project, the time taken to finish it, the deadline, and the profit you can gain, in order to decide if your group should take this project. For example, given 3 projects as the following:

  • Project[1] takes 3 days, it must be finished in 3 days in order to gain 6 units of profit.
  • Project[2] takes 2 days, it must be finished in 2 days in order to gain 3 units of profit.
  • Project[3] takes 1 day only, it must be finished in 3 days in order to gain 4 units of profit.

You may take Project[1] to gain 6 units of profit. But if you take Project[2] first, then you will have 1 day left to complete Project[3] just in time, and hence gain 7 units of profit in total. Notice that once you decide to work on a project, you have to do it from beginning to the end without any interruption.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤50), and then followed by N lines of projects, each contains three numbers P, L, and D where P is the profit, L the lasting days of the project, and D the deadline. It is guaranteed that L is never more than D, and all the numbers are non-negative integers.

Output Specification:

For each test case, output in a line the maximum profit you can gain.

Sample Input:

4
7 1 3
10 2 3
6 1 2
5 1 1

Sample Output:

18

解题思路

很明显是一个01背包的题目,在dp前要先按照r从小到大排序,因为有一个deadline(在deadline之前完成就行了,不一定非要在这天完成,博主理解错了然后自闭了),所以对于一个任务来说,它所对应的背包容量就变成了deadline,不能超出这个点。 然后输出dp[]的最大值。之所以要最大值而不是最大容量的那个值,见代码注释(没错,这个坑我又掉进去了,再次自闭)。

代码如下

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
using namespace std;
struct Pro{
	int v, r, w;
	Pro(int v, int r, int w): v(v), r(r), w(w){ 	}
};
bool cmp(Pro a, Pro b)
{
	return a.r < b.r;
}
vector<Pro> pro;
int main()
{
	int n;
	while(cin >> n){ 
		for(int i = 0; i < n; i ++){
			int p, l, d;
			cin >> p >> l >> d;
			pro.push_back(Pro(l, d, p));
		}
		sort(pro.begin(), pro.end(), cmp);
		map<int, int> dp;
		int maxx = -1;
		for(int i = 0; i < pro.size(); i ++){
			for(int j = pro[i].r; j >= 1; j --){         
				dp[j] = max(dp[j], dp[j - pro[i].v] + pro[i].w);//当j比较大的时候j-pro[i].v的值可能大于上一个任务的deadline(r)  
				maxx = max(dp[j], maxx);                        //而这中间的部分没有赋值还是0,所以后面可能不如前面大
			}                                                   
		}
		cout << maxx << endl;
		pro.clear();
	}
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值