题意:n个栅栏,m个工人,每个工人在位置s,能刷的长度为l,赚的钱为p,问怎么安排使得赚钱最大
思路:先按工人位置排序,然后dp[i][j]表示i个工人刷了j个栅栏的最大值,那么这个转移dp[i][j] = max(dp[i - 1][k] + cost[i] * (j - k),时间复杂度有点无法接受,需要进行优化,
把状态转移进行转化,dp[i - 1][k] - cost[i] * k + cost[i][j],在枚举i,j的时候,后面那个值相当于一个常数,那么利用一个单调队列,把前面那部份的值,边枚举边维护下来,这样每次取就只是O(1)的复杂度了
代码:
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 105;
const int M = 16005;
const int INF = 0x3f3f3f3f;
int n, m;
int l, p[N], s;
int dp[N][M];
struct Work {
int l, p, s;
void read() {
scanf("%d%d%d", &l, &p, &s);
}
} work[N];
bool cmp(Work a, Work b) {
return a.s < b.s;
}
int Q[M];
int main() {
while (~scanf("%d%d", &m, &n)) {
for (int i = 1; i <= n; i++) work[i].read();
sort(work + 1, work + n + 1, cmp);
for (int i = 1; i <= n; i++) {
l = work[i].l; p[i] = work[i].p; s = work[i].s;
int head = 0, rear = 0;
Q[rear++] = max(s - l, 0);
for (int j = 1; j <= m; j++) {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
if (j >= s + l) continue;
while (head < rear && Q[head] + l < j)
head++;
if (j < s) {
int tmp = dp[i - 1][j] - j * p[i];
while (head < rear && dp[i - 1][Q[rear - 1]] - Q[rear - 1] * p[i] < tmp)
rear--;
Q[rear++] = j;
continue;
}
dp[i][j] = max(dp[i][j], dp[i - 1][Q[head]] + p[i] * (j - Q[head]));
}
}
printf("%d\n", dp[n][m]);
}
return 0;
}