题解:P17833 [CSP-S 2026] 迁徙 / migrate(民间数据)
谨以此题解纪念我失败的 CSP-S 2026。因为 T3 没调出来与 WC 失之交臂。
首先假设我们钦定左端点,我们可以想到一个容易的 dp,大概是
我们设
这样每个左端点跑一遍可以做到
然后我们进行观察,首先显而易见的
那么我们把一个
我们设
转移时我们只需要考虑往后跳一个状态,加上这里和下一个连续段后两个位置之前产生的那些贡献即可。
往后跳的下一个状态这里是一个稍微有点屎的分讨,具体看代码吧。需要两个辅助数组
总共只有
整体时间复杂度
下面是考后重写的代码,还是有些细节的。
#include <bits/stdc++.h>
#define N 2000010
#define int long long
using namespace std;
const int INF = 1e18;
int c, t, n, d, x[N];
int bk[N], nt1[N], nt2[N];
int dp[N][3][3];
struct Node {int u, c1, c2;} ed;
typedef pair <Node, int> P;
P mv(Node nw) {
int u = nw.u, c1 = nw.c1, c2 = nw.c2;
if(nt1[u] == INF && nt1[u - 1] == INF || c2 == 2) return {ed, (c1 == 1) + (c2 == 1)};
if(c2 == 1) { // ? 2
if(nt1[u] == INF) return {ed, (c1 == 1) + 1};
else if(nt1[u] == nt2[u]) return {{nt2[u], 2, 1}, (c1 == 1) + 1};
else return {{nt2[u], 1, 1}, (c1 == 1) + 1 + (nt2[u] - nt1[u] - 1)};
}
if(c1) { // >1 1
if(nt1[u] == INF) return {ed, (c1 == 1)};
else if(nt1[u] == nt2[u]) return {{nt2[u], 2, 0}, (c1 == 1)};
else return {{nt2[u], 0, 0}, (c1 == 1)};
}
// 1 1
if(nt1[u] == INF) {
if(nt1[u - 1] == nt2[u - 1]) return {{nt2[u - 1], 2, 1}, 0};
else return {{nt2[u - 1], 1, 1}, nt2[u - 1] - nt1[u - 1] - 1};
}
if(nt1[u - 1] == INF) {
if(nt1[u] == nt2[u]) return {{nt2[u], 2, 0}, 0};
else return {{nt2[u], 0, 0}, 0};
}
if(nt1[u] == nt2[u]) return {{nt2[u], 1, 0}, nt2[u - 1] - nt1[u - 1]};
else return {{nt2[u], 0, 0}, nt2[u - 1] - nt1[u - 1] + 1};
}
signed main() {
freopen("migrate.in", "r", stdin);
freopen("migrate.out", "w", stdout);
cin.tie(0) -> sync_with_stdio(0);
cin >> c >> t;
while(t--) {
cin >> n >> d;
for(int i = 1; i <= n; i++) cin >> x[i];
int l = 1;
for(int i = 1; i <= n; i++) {
while(x[i] - x[l] > d) l++;
if(l == i) bk[i] = -1;
else bk[i] = l;
}
for(int i = 1; i <= n; i++) {nt1[i] = INF; nt2[i] = 0;}
for(int i = 1; i <= n; i++)
if(bk[i] != -1) {
nt1[bk[i]] = min(nt1[bk[i]], i);
nt2[bk[i]] = max(nt2[bk[i]], i);
}
ed = {n + 1, 0, 0}; dp[n + 1][0][0] = 0;
for(int i = n; i >= 2; i--)
for(int j = 0; j < 3; j++)
for(int k = 0; k < 3; k++) {
P tmp = mv({i, j, k});
Node nxt = tmp.first;
dp[i][j][k] = dp[nxt.u][nxt.c1][nxt.c2] + tmp.second;
}
int r = 1, ans = 0;
for(int i = 1; i <= n; i++) {
while(r < n && x[r + 1] - x[i] <= d) r++;
if(r == i) continue;
if(r == i + 1) ans += dp[r][2][0];
else ans += dp[r][0][0];
}
cout << ans << '\n';
}
return 0;
}
场上 50min 想到了这个并没有多高思维门槛的做法,然而 1.5h 无法调出,遗憾与 WC 失之交臂,空悲切。