单调栈、单调队列优化DP
T1 P1725 琪露诺
题意: 琪露诺需要从编号 0 的格子出发,每次可以从格子
思路
普通动态规划: 设
但是直接暴力求解时间复杂度为
code
#include<bits/stdc++.h>
using namespace std;
const int N = 4e5+5;
const int inf = 1e9;
int n, L, R, a[N], dp[N];
int h = 0, t = -1, q[N];
int ans = -inf;
int main() {
cin >> n >> L >> R;
for (int i = 0; i <= n; i++) {
cin >> a[i];
dp[i] = -inf;
}
dp[0] = 0;
for (int i = L; i <= n + R; i++) {
int j = i - L;
if (j >= 0 && j <= n + R) {
while (h <= t && dp[q[t]] <= dp[j])
t--;
q[++t] = j;
}
while (h <= t && q[h] < i - R)
h++;
if (h <= t) dp[i] = dp[q[h]] + a[i];
else dp[i] = -inf;
if (i > n) ans = max(ans, dp[i]);
}
cout << ans;
return 0;
}
T2 River Crossing
题意: 小明要从西岸(位置
思路
使用动态规划:设
也就是说,到达石头
优化 直接计算的时间复杂度是
code
#include<bits/stdc++.h>
using namespace std;
const int MOD = 1e9+7, M = 150007;
int N, W, L, R;
int x[M], dp[M], a[M];
int main() {
cin >> N >> W >> L >> R;
for (int i = 1; i <= N; i++)
cin >> x[i];
dp[0] = a[1] = 1;
x[N + 1] = W;
for (int i = 1; i <= N + 1; i++) {
int lv = x[i] - R, rv = x[i] - L;
int li = lower_bound(x, x + i, lv) - x;
int ri = upper_bound(x, x + i, rv) - x - 1;
if (li <= ri && li >= 0) {
long long sum = a[ri + 1] - a[li];
dp[i] = (sum % MOD + MOD) % MOD;
}
a[i + 1] = (a[i] + dp[i]) % MOD;
}
cout << dp[N + 1];
return 0;
}