跳到正文

题解

宇宙射线

Mier_Samuelle约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年7月8日
更新
2026年7月12日
篇幅
约 3 分钟
获赞
2
题目
P16996

版本

  1. v1当前

挺有意思的一道题。

先回顾一下冒泡排序是怎么做的。一共要跑 nn 趟排序,其中第 ii 趟会通过交换相邻元素,将序列中第 ii 大的元素挪到正确的位置上,本题中就是将 n−i+1n-i+1 挪到下标 n−i+1n-i+1 处。

假设宇宙射线影响了第 ii 趟排序,导致 n−i+1n-i+1 没有被挪到正确的位置上。设此时 ax=n−i+1a_x=n-i+1,且 aya_y 最终占据了下标 n−i+1n-i+1,则:

  • 若 x<yx<y,即 axa_x 在 aya_y 左边,则 axa_x 会不断向右挪,直到与 aya_y 相邻,此时发生错误,axa_x 没有和 aya_y 交换,然后 aya_y 不断向右挪,挪到 n−i+1n-i+1 为止。这就要求 aya_y 是区间 [y,n−i+1][y,n-i+1] 内的最大值。
  • 若 x>yx>y,即 axa_x 在 aya_y 右边,则 aya_y 会不断向右挪,直到与 axa_x 相邻,此时发生错误,axa_x 和 aya_y 交换,然后 aya_y 不断向右挪,挪到 n−i+1n-i+1 为止。这就要求 aya_y 是区间 [1,x)∪(x,n−i+1][1,x) \cup (x,n-i+1] 内的最大值,即 n−in-i。

第一类贡献可用单调栈 O(n)O(n) 统计,第二类贡献可简单地 O(1)O(1) 统计,一共要跑 nn 趟排序,所以是 O(n2)O(n^2) 的,不可接受。

瓶颈在于每次都跑一遍单调栈,考虑只跑一次。容易发现,栈的深度减 11 恰好就是 n−i+1n-i+1 右边的后缀最大值个数,即第一类贡献。第二类贡献也是容易统计的,因为若 n−in-i 在栈内,则一定是紧挨着 n−i+1n-i+1 的,而不在栈内的情况就是会产生贡献的情况。跑完一趟排序后,更新单调栈可做到 O(1)O(1)。至此,我们便可以 O(n)O(n) 统计贡献了。

然而还有一个 corner case,即宇宙射线没有影响排序的结果。容易发现,此时错误一定发生在 n−i+1n-i+1 左边的某两个元素上,即只要 x>2x>2,就有可能出现这种情况。记录一下最大值的位置即可。

Code (209 ms / 60.61 MB)
C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 2e6 + 10;
int a[MAXN], s[MAXN];
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++){
		cin >> a[i];
	}
	int t = 0;
	for (int i = n; i >= 1; i--){
		if (a[i] > s[t]){
			s[++t] = a[i];
		}
	}
	int ans = 0;
	for (int i = n; i >= 2; i--){
		ans += t - 1;
		if (t > 1 && s[t] == s[t - 1] + 1){
			t--;
		}
		else{
			s[t]--;
			ans++;
		}
	}
	int pos1 = 1, pos2 = 2, nxt = 3, flag = 0;
	for (int i = n; i >= 2; i--){
		if (a[pos1] == i){
			pos1 = pos2;
			pos2 = nxt;
			nxt++;
		}
		else if (a[pos2] == i){
			pos2 = nxt;
			nxt++;
		}
		else{
			flag = 1;
			break;
		}
	}
	ans += flag;
	cout << ans << endl;
	return 0;
}
原文