pat考试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 (≤), 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

做过类似的贪心题,但是这题好像不能贪心,于是我们动态规划,又由于题目并没有明确数据范围(又是坑爹),所以我们可以map来表示二维数组。
我们先做一个排序,按照截止时间排序。
然后dp[i][j]表示第i个任务在第j天刚好结束时的最大收益。转移是O(n)的。
 1 #include<bits/stdc++.h>
 2 using namespace std;  
 3 #define mp  make_pair
 4 #define fi  first  
 5 #define se  second  
 6 int const N=50+3;  
 7 map<pair<int,int>,int> dp;   
 8 int p[N],L[N],d[N],n;  
 9 int main(){ 
10     scanf("%d",&n);  
11     for(int i=1;i<=n;i++)  
12         scanf("%d%d%d",&p[i],&L[i],&d[i]);  
13     for(int i=1;i<=n;i++)   
14         for(int j=i+1;j<=n;j++)  
15             if(d[i]>d[j]){
16                 swap(p[i],p[j]);  
17                 swap(L[i],L[j]);  
18                 swap(d[i],d[j]); 
19             }
20     int ans=0;  
21     for(int i=1;i<=n;i++)  
22         for(int j=L[i];j<=d[i];j++)  
23             dp[mp(i,j)]=p[i],ans=max(ans,p[i]);  
24     for(int i=1;i<n;i++)  
25         for(int j=1;j<=d[i];j++){
26             if(dp.find(mp(i,j))==dp.end()) continue;  
27             int x=dp[mp(i,j)];  
28             for(int k=i+1;k<=n;k++) 
29                 if(j+L[k]<=d[k]){
30                     int &t=dp[mp(k,j+L[k])];  
31                     t=max(t,x+p[k]);   
32                     ans=max(t,ans);   
33                 }
34         }
35     printf("%d\n",ans); 
36     return 0; 
37 }
View Code

 

posted @ 2019-09-11 11:02  zjxxcn  阅读(270)  评论(0编辑  收藏  举报