题解:CF2229G Roadworks
Encounter_k · · 题解
一个比较显然的观察是,在路程中,如果在一个房子
于是可以得出,当走到一个可能产生停留的房子时,后续一定是到达它左 / 右第一个
同时,对于在路程中去的每一个关键点,到达它时一定是在最早可到达它(即路通并且天数够到达它)的那一天。否则它相当于在一些,非必要经过的点上多停留了,那么扔掉这些点改成这个关键点一定是更优的。
于是我们求出
所以,对于关键点
求出对于每个点
#include <bits/stdc++.h>
using namespace std;
#define int long long
int n, k, x, h[200005], d[200005], mn[200005], lft[200005], rgt[200005];
int sum[200005], dp[200005];
void solve() {
cin >> n >> k >> x;
for (int i = 0; i <= n + 1; i++) {
lft[i] = rgt[i] = -1;
mn[i] = -1e18;
}
for (int i = 1; i <= n; i++) {
cin >> h[i];
sum[i] = sum[i - 1] + h[i];
}
for (int i = 1; i < n; i++) {
cin >> d[i];
}
mn[x] = 1;
if (x < n && d[x] == 1) {
mn[x + 1] = 1;
} else if (x < n) {
mn[x + 1] = max(mn[x] + 1, d[x]);
}
if (x > 1 && d[x - 1] == 1) {
mn[x - 1] = 1;
} else if (x > 1) {
mn[x - 1] = max(mn[x] + 1, d[x - 1]);
}
for (int i = x + 2; i <= n; i++) {
mn[i] = max(mn[i - 1] + 1, d[i - 1]);
}
for (int i = x - 2; i >= 1; i--) {
mn[i] = max(mn[i + 1] + 1, d[i]);
}
stack<int> st;
st.push(1);
for (int i = 2; i <= n; i++) {
while (!st.empty() && h[st.top()] <= h[i]) {
st.pop();
}
if (!st.empty()) {
lft[i] = st.top();
}
st.push(i);
}
while (!st.empty()) {
st.pop();
}
st.push(n);
for (int i = n - 1; i >= 1; i--) {
while (!st.empty() && h[st.top()] <= h[i]) {
st.pop();
}
if (!st.empty()) {
rgt[i] = st.top();
}
st.push(i);
}
for (int i = 0; i <= n; i++) {
dp[i] = -1e18;
}
queue<pair<int, int>> q;
for (int i = max(1ll, x - 1); i <= min(n, x + 1); i++) {
if (mn[i] == 1) {
dp[i] = 0;
q.push({0, i});
}
}
while (!q.empty()) {
pair<int, int> f = q.front();
q.pop();
if (dp[f.second] != f.first) {
continue;
}
if (lft[f.second] != -1) {
if (mn[lft[f.second]] - mn[f.second] >= abs(lft[f.second] - f.second)) {
int len = max(lft[f.second], f.second) - min(lft[f.second], f.second) - 1;
int v = dp[f.second] + sum[max(lft[f.second], f.second) - 1] - sum[min(lft[f.second], f.second)] + h[f.second] * (mn[lft[f.second]] - mn[f.second] - len);
if (dp[lft[f.second]] < v) {
dp[lft[f.second]] = v;
q.push({v, lft[f.second]});
}
}
}
if (rgt[f.second] != -1) {
if (mn[rgt[f.second]] - mn[f.second] >= abs(rgt[f.second] - f.second)) {
int len = max(rgt[f.second], f.second) - min(rgt[f.second], f.second) - 1;
int v = dp[f.second] + sum[max(rgt[f.second], f.second) - 1] - sum[min(rgt[f.second], f.second)] + h[f.second] * (mn[rgt[f.second]] - mn[f.second] - len);
if (dp[rgt[f.second]] < v) {
dp[rgt[f.second]] = v;
q.push({v, rgt[f.second]});
}
}
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
if (dp[i] >= 0 && mn[i] <= k) {
ans = max(ans, dp[i] + (k - mn[i] + 1) * h[i]);
}
}
cout << ans << "\n";
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int tt;
cin >> tt;
while (tt--) {
solve();
}
return 0;
}