在一个项目的截止日期之前,如果工期有空闲则可能可以开展其他项目,提高效益。本题考查动态规划。数组dp[i][t]表示在截止时间为t时,前i个项目工作安排能够产生的最大收益,而前i个项目的截止时间都不大于t。
//#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <memory.h> using namespace std; struct node { // project struct
int p, l, d; // p is the profit, l is the lasting days of the project, d is the deadline
}pro[]; int cmp(node a, node b) { // sort rule
return a.d < b.d;
} int main() {
int n;
scanf("%d", &n); int i, maxd = ;
for (i = ; i <= n; i++) {
scanf("%d%d%d", &pro[i].p, &pro[i].l, &pro[i].d); if (pro[i].d > maxd) { // get the max deadline
maxd = pro[i].d;
}
} sort(pro + , pro + n + , cmp); int** dp = new int*[n + ];
for (i = ; i <= n; i++) {
dp[i] = new int[maxd + ];
memset(dp[i], , sizeof(dp[i])); // initialization : set value zero
} //printf("%d\n", dp[0][0]);
int j, t;
for (i = ; i <= n; i++) {
for (j = ; j <= maxd; j++) {
t = min(j, pro[i].d) - pro[i].l;
// get the max profit
if (t >= ) { // if can plus current project to compare the profit
dp[i][j] = max(pro[i].p + dp[i - ][t], dp[i - ][j]);
} else { // otherwise
dp[i][j] = dp[i - ][j];
}
}
} printf("%d\n", dp[n][maxd]); for (i = ; i <= n; i++) {
delete[] dp[i];
}
delete[] dp; system("pause");
return ;
}
参考资料