跳到正文

题解

High Elements

xht约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 6 分钟
获赞
2

版本

  1. v1当前

High Elements

题意

  • 给定一个 1∼n1 \sim n 的排列 pp。
  • 求出字典序最小的满足下列条件的 0/10/1 串 s1…ns_{1\dots n},或判断不存在:
    • 一开始有两个空序列 x,yx,y。
    • 依次考虑 i∈[1,n]i \in [1,n],若 sis_i 为 0 则将 pip_i 加入 xx 末尾,否则加入 yy 末尾。
    • x,yx,y 中为前缀 max⁡\max 的位置数量相同。
  • n≤2×105n \le 2\times 10^5。

题解

看到字典序显然贪心,现在前 i−1i-1 位已经确定,考虑第 ii 位,先假设为 0,如果不合法则改成 1。接下来的问题就是如何判断是否合法。

首先可以证明,如果存在合法的 ss,必然可以使得 x,yx,y 两个数列中,有一个数列的前缀 max⁡\max 都是 pp 中的前缀 max⁡\max。这是因为如果不是,交换两个不是 pp 中前缀 max⁡\max 的前缀 max⁡\max 可以把这两个前缀 max⁡\max 都消掉。

不妨假设 xx 中的前缀 max⁡\max 都由 pp 的前缀 max⁡\max 构成,令 x,yx,y 当前的前缀 max⁡\max 个数为 cx,cyc_x,c_y,pi…np_{i\dots n} 中前缀 max⁡\max 个数为 cpc_p。设 yy 中将会有 kk 个前缀 max⁡\max 也是 pp 的前缀 max⁡\max,则 xx 中会有 cp−kc_p - k 个。再设 yy 中不是 pp 的前缀 max⁡\max 的前缀 max⁡\max 个数为 mm,我们能得到等式:

cx+cp−k=cy+k+mc_x + c_p - k = c_y + k + m

即:

2k+m=cp+cx−cy2k+m = c_p+c_x-c_y

其中右边是常量,设为 cc。

由于在 x>0x>0 或 y>1y>1 时可以从 2k+m2k+m 的方案构造出减少 22 的方案,因此若满足存在 2k+m≥c2k+m \ge c 且 2k+m≡c(mod2)2k+m \equiv c \pmod 2,就存在合法解。

考虑 2k+m2k+m,相当于我们把 pp 中的前缀 max⁡\max 的权值设为 22,其它位置的权值设为 11 后的带权最长上升子序列长度。

于是用权值线段树维护单点修改和区间求 max⁡\max,求出 fi,0/1f_{i,0/1} 从 ii 开始长度为偶/奇数的带权最长上升子序列的长度,判断时用类似的操作求出 2k+m2k + m 在偶/奇数下的最大值即可。

由于我们的贪心策略默认了有解,所以最后如果 cx≠cycx \ne cy 则说明无解。

时间复杂度 O(nlog⁡n)\mathcal O(n\log n)。

代码

C++
const int N = 2e5 + 7, inf = 1e9;
int n, p[N], c[N], cx, cy;
bool v[N];
char s[N];

struct SGT {
	struct T {
		int l, r, x;
	} t[N<<2|1];

	inline void update(int p) {
		t[p].x = max(t[ls].x, t[rs].x);
	}

	void build(int p, int l, int r, int x) {
		t[p].l = l, t[p].r = r;
		if (l == r) return t[p].x = x, void();
		build(ls, l, md, x), build(rs, md + 1, r, x);
		update(p);
	}

	void add(int p, int x, int k) {
		if (t[p].l == t[p].r) return t[p].x = k, void();
		if (x <= md) add(ls, x, k);
		if (x > md) add(rs, x, k);
		update(p);
	}

	int ask(int p, int l, int r) {
		if (t[p].l >= l && t[p].r <= r) return t[p].x;
		int ret = -inf;
		if (l <= md) ret = max(ret, ask(ls, l, r));
		if (r > md) ret = max(ret, ask(rs, l, r));
		return ret;
	}
} t[2];

inline bool pd(int x, int k) {
	return k < 0 ? 0 : t[k&1].ask(1, x, n) >= k;
}

int main() {
	rd(n), rda(p, n);
	for (int i = 1, x = 0; i <= n; i++)
		if (p[i] > x) x = p[i];
		else v[i] = 1;
	t[0].build(1, 1, n, 0), t[1].build(1, 1, n, -inf);
	for (int i = n; i; i--) {
		int x0 = t[0].ask(1, p[i], n), x1 = t[1].ask(1, p[i], n);
		t[0].add(1, p[i], (v[i] ? x1 + 1 : x0 + 2));
		t[1].add(1, p[i], (v[i] ? x0 + 1 : x1 + 2));
		c[i] = c[i+1] + !v[i];
	}
	for (int i = 1, x = 0, y = 0; i <= n; i++) {
		t[0].add(1, p[i], 0), t[1].add(1, p[i], -inf);
		if (pd(y, c[i+1] + cx - cy + (p[i] > x)) || pd(max(x, p[i]), c[i+1] + cy - cx - (p[i] > x)))
			s[i] = '0', cx += p[i] > x, x = max(x, p[i]);
		else s[i] = '1', cy += p[i] > y, y = max(y, p[i]);
	}
	if (cx == cy) prints(s, n);
	else print(-1);
	return 0;
}
原文