想到了该用dp,0-1背包问题的思路,但转移方程想不出来,最终参考了pat顶级1002 Business (35 分)_日沉云起的博客-CSDN博客
的思路。
dp[i][j]表示在0,1,2,...,i项任务中选择,在j天内能达到的最大利润。任务按最终期限排序(因为肯定是先做deadline比较前面的任务再做后面截止的任务)。
#include <cstdio>
#include <vector>
#include <algorithm>
const int maxN = 51;
struct project{
int profit, len, deadline;
};
int N, maxDeadline;
std::vector<project> vec;
std::vector<int> dp[maxN];
bool cmp(const project &a, const project &b){
return a.deadline < b.deadline;
}
int main(){
scanf("%d", &N);
vec.resize(N);
maxDeadline = 0;
for(int i = 0; i < N; ++i){
scanf("%d %d %d", &vec[i].profit, &vec[i].len, &vec[i].deadline);
maxDeadline = std::max(maxDeadline, vec[i].deadline);
}
sort(vec.begin(), vec.end(), cmp);
for(int i = 0; i < N; ++i){
dp[i].resize(maxDeadline + 1);
for(int j = 1; j <= maxDeadline; ++j){
if(i == 0){
if(j < vec[i].len){
dp[i][j] = 0;
} else{
dp[i][j] = vec[i].profit;
}
} else{
if(j < vec[i].len){
dp[i][j] = dp[i - 1][j];
} else{
dp[i][j] = std::max(dp[i - 1][j], dp[i - 1][std::min(j, vec[i].deadline) - vec[i].len] + vec[i].profit);
}
}
}
}
printf("%d", dp[N - 1][maxDeadline]);
return 0;
}
题目如下:
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, Lthe 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