标签:优化 amp min class its void can main http
https://www.luogu.org/problemnew/show/P2418
暴力 DP 做这题只有 30 分
考虑用线段树优化这个 DP
先处理一下整个房间都膜拜一个人的情况,然后将 1 的当成 -1, 2 当成 1,处理前缀和,可以发现对于前缀和为 x 的情况,只能从前缀和为 [x - k, x + k] 的地方转移过来,用线段树维护 DP 数组的最小值就行了
#include <bits/stdc++.h>
using namespace std;
const int N = 500000 + 10;
int minn[N << 3], a[N], s[N], f[N];
int n, k, last;
void change(int u, int l, int r, int x, int y) {
minn[u] = min(minn[u], y);
if(l == r) return;
int mid = (l + r) >> 1;
if(mid >= x) change(u << 1, l, mid, x, y);
else change(u << 1 | 1, mid + 1, r, x, y);
}
int Q;
void query(int u, int l, int r, int L, int R) {
if(l <= L && R <= r) {
Q = min(Q, minn[u]);
return;
}
int mid = (L + R) >> 1;
if(mid >= l) query(u << 1, l, r, L, mid);
if(mid + 1 <= r) query(u << 1 | 1, l, r, mid + 1, R);
}
int main() {
memset(minn, 0x3f, sizeof(minn));
cin >> n >> k; s[0] = N;
for(int i = 1; i <= n; i++) {
int t; scanf("%d", &t);
if(t == 1) a[i] = -1;
else a[i] = 1;
s[i] = s[i - 1] + a[i];
}
change(1, 1, n + k + N, N, 0);
for(int i = 1; i <= n; i++) {
if(a[i] != a[i - 1]) last = f[i - 1];
else last = min(last, f[i - 1]);
f[i] = last + 1;
Q = INT_MAX;
query(1, s[i] - k, s[i] + k, 1, n + k + N);
f[i] = min(f[i], Q + 1);
change(1, 1, n + k + N, s[i], f[i]);
}
cout << f[n] << endl;
return 0;
}
标签:优化 amp min class its void can main http
原文地址:https://www.cnblogs.com/LJC00118/p/9607239.html