PAT 1002. Business (35)

来源:互联网 发布:mysql truncate函数 编辑:程序博客网 时间:2024/05/22 02:57

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

#include<iostream>using namespace std;int Projects[55][3];int dp[55][1000];int max(int a, int b){  return a >= b ? a : b;}void swap(int i, int j, int projects[][3]){  int a, b, c;  a = projects[i][0];  b = projects[i][1];  c = projects[i][2];  projects[i][0] = projects[j][0];  projects[i][1] = projects[j][1];  projects[i][2] = projects[j][2];  projects[j][0] = a;  projects[j][1] = b;  projects[j][2] = c;}int min(int a, int b){  return a >= b ? b : a;}void sort_by_deadline(int projects[][3], int N){  for(int i = 0; i < N; i++){    int min = projects[i][2];    int index = i;    for(int j = i + 1; j < N; j++){      if(min > projects[j][2]){        index = j;        min = projects[j][2];      }    }    swap(i, index, projects);  }}int main(){  int N;  cin >> N;  for(int i = 0; i < N; i++){    cin >> Projects[i][0] >> Projects[i][1] >> Projects[i][2];  }  sort_by_deadline(Projects, N);  for(int i = 0; i < N; i++){    for(int j = 0; j <= Projects[N-1][2]; j++){      dp[i][j] = 0;    }  }  for(int i = 0; i < N; i++){    for(int j = 1; j <= Projects[N-1][2]; j++){      int tem_min = min(j, Projects[i][2]) - Projects[i][1];      if(tem_min >= 0)        dp[i+1][j] = max(dp[i][j], dp[i][tem_min] + Projects[i][0]);      else        dp[i+1][j] = dp[i][j];    }  }  cout << dp[N][Projects[N-1][2]] << endl;  return 0;}

数组dp[i][j],表示在截止时间为t时,前i个项目工作安排能够得的最大收益。
可得方程:dp[i][t]=max(dp[i-1][t],dp[i-1][t’]+proj[i].p)其中t’ 等于min(t, 工程 i 截止时间)- 工程 i 所需时间

原创粉丝点击