跳到正文

题解

题解:CF2161D Locked Out

cbcyh约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年12月25日
收录
2026年6月5日
更新
2026年11月10日
篇幅
约 5 分钟
获赞
2
题目
CF2161D

版本

  1. v1当前

先将 aa 数组按 aia_i 从小到大排序,aia_i 相同的按下标从大到小的顺序放,且令 bib_i 为排好序后第 ii 项的值,cic_i 为排好序后第 ii 项在原数组中的下标。
考虑动态规划,令 fif_i 为考虑了排好序后前 ii 项,能保留的最多数目。
转移如下:
fi←max⁡(1,max⁡1≤j<i(bj≠bi−1∨ci<cj)(dpj+1))f_i \leftarrow \max\left(1, \max_{\substack{1 \le j < i \\ (b_j \neq b_i - 1 \lor c_i < c_j)}} (dp_j + 1)\right)
直接做时间复杂度是 O(n2)\mathcal{O(n^2)} 的。我们来优化这个转移。
这个转移可以分为 22 部分来优化:

  • bj<bi−1b_j<b_i-1 的 fjf_j 最大值。这一部分可以直接动态的用一个变量来维护。也可以像我代码中写的一样用一个指针来扫,在扫的过程中动态维护。
  • ci<cjc_i<c_j 的最大值。这一部分可以统一把下标转化为 n+1−in+1-i,转化后就可以用树状数组维护前缀最大值,来代替原问题的后缀最大值。说实话我还是第一次见树状数组维护最大值的

这样,我们就解决了此问题。下面是代码。 AC link

C++
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define unll unsigned long long
#define bint __int128
#define set_q priority_queue
#define unmp unordered_map
#define ldouble long double
mt19937_64 mrand((unll) std::chrono::steady_clock::now().time_since_epoch().count());

inline int in() {
	unsigned int x = 0ll; bool f = false; char ch = getchar();
	while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
	while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
	return f ? -(int)x : x;
}

inline ll inll() {
	unll x = 0ll; bool f = false; char ch = getchar();
	while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
	while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
	return f ? -(ll)x : x;
}

const ll inf = 1ll << 59ll;
const ll infless = -inf;

const int N = 300100;

int test, n, s[N], f[N];
array<int, 2> a[N];
ll ans = 0ll, res = 0ll;

inline int lowbit (const int &x) {
	return x & (-x);
}

inline int query (const int &x) {
	int sum = 0;
	for (int y = x; y; y -= lowbit(y)) {
		sum = max(sum, s[y]);
	}
	return sum;
}

inline void modify (const int &x, const int &d) {
	for (int y = x; y <= n; y += lowbit(y)) {
		s[y] = max(s[y], d);
	}
}

inline void solve () {
	ans = 0ll;
	n = in();
	for (int i = 1; i <= n; i++) {
		a[i] = {in(), n + 1 - i};
		f[i] = s[i] = 0;
	}
	sort(a + 1, a + n + 1);
	int j = 0;
	res = 0ll;
	for (int i = 1; i <= n; i++) {
		while (j + 1 < i && a[j + 1][0] + 1 < a[i][0]) {
			j++;
			res = max(res, 1ll * f[j]);
		}
		f[i] = 1 + max((int)res, query(a[i][1]));
		modify(a[i][1], f[i]);
		ans = max(ans, 1ll * f[i]);
		//printf("x%d %d %d\n", i, j, f[i]);
	}
	printf("%lld\n", n - ans);
	return;
}

int main() {
	for (test = in(); test--; solve());
	return 0;
}
原文