题目链接
题目如下:
![](https://i-blog.csdnimg.cn/blog_migrate/9ec583b5f7fb90965afaebe74ad71162.png)
题目大意
![](https://i-blog.csdnimg.cn/blog_migrate/a3b2b0f7bc74592c033cb76663fa78d7.png)
解题思路
一眼dp。
可以套用三重循环解如下:
for (int i = 1; i <= m; i++) {
long long k = 1, td = t[i] - t[i - 1];
for (int j = 1; j <= n; j++) {
long long tem = -1e18;
for (int k = std::max(1ll, j - d * (t[i] - t[i - 1])); k <= std::min(n, j + d * (t[i] - t[i - 1])); k++) {
tem = std::max(tem, dp[!flag][k]);
}
dp[flag][j] = tem + b[i] - (long long)fabs(a[i] - j);
// printf("%4lld ", dp[flag][j]);
}
// printf("\n");
flag ^= 1;
}
这样时间复杂度最坏为O(mn²),肯定TLE
接下来考虑优化,观察发现k的循环是找出一个区间中的最大值,而且这个区间随着j移动,仔细观察这句话你就会发现,这不是窗口滑动(单调队列模板)吗,于是我们就愉快的有单调队列进行优化。
代码如下:
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <deque>
const int maxn = 151234;
const int maxm = 312;
long long dp[2][maxn];
long long a[maxm], b[maxm], t[maxm];
std::deque<long long> q, p;
inline void read(long long &x) {
x = 0;
short flag = 1;
char c = getchar();
while (c < '0' || c > '9') {
if (c == '-')
flag = -1;
c = getchar();
}
while (c >= '0' && c <= '9') {
x = (x << 3) + (x << 1) + (c ^ 48);
c = getchar();
}
x *= flag;
}
long long n, m, d;
int main() {
read(n);
read(m);
read(d);
t[0] = 1;
long long ans = -1e18;
int flag = 1;
for (int i = 1; i <= m; i++) {
read(a[i]);
read(b[i]);
read(t[i]);
}
for (int i = 1; i <= m; i++) {
long long k = 1, td = t[i] - t[i - 1];
q.clear();
p.clear();
for (int j = 1; j <= n; j++) {
long long tem = -1e18;
for (; k <= std::min(n, j + d * td); k++) {
while (!q.empty() && q.back() < dp[!flag][k]) {
q.pop_back();
p.pop_back();
}
q.push_back(dp[!flag][k]);
p.push_back(k);
}
while (p.front() < j - d * td) {
q.pop_front();
p.pop_front();
}
dp[flag][j] = q.front() + b[i] - (long long)fabs(a[i] - j);
}
flag ^= 1;
}
flag ^= 1;
for (int i = 1; i <= n; i++)
ans = std::max(ans, dp[flag][i]);
printf("%lld", ans);
}