跳到正文

题解

题解:P17177 Check Check Permutation Clear

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

文章信息

收录
2026年8月2日
更新
2026年8月4日
篇幅
约 5 分钟
获赞
1
题目
P17177

版本

  1. v3当前
  2. v2
  3. v1

题目传送门

思路

题目中 nn 最大能达到 3×1073 \times 10^7,且时限仅 500ms500\text{ms},必须使用线性 O(n)\mathcal{O(n)} 做法,那么考虑单调栈模拟。

设全局最大值 MM 出现在位置 pospos。

若存在某个 i>posi>pos,满足 ai<Ma_i<M:

  • MM 在 aia_i 前面,M>aiM>a_i,构成一组逆序对
  • MM 不在 aia_i 紧邻的连续大数段里
  • 这组逆序对不会被计入弹栈次数 cc 于是 c<invc < inv,不满足条件。

反过来,全程所有数字都比之前全局最大值更大:

  • 没有任何逆序对,inv=0inv=0
  • 栈不会弹出任何元素 c=0c=0 ,满足 c=invc=inv

只要任何位置出现数字小于目前全局最大值且不是紧跟在最大值后面,直接不合法。

代码

AC Code
C++
#include <bits/stdc++.h> 
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
#define rep(x, y, z) for (int x = (y); x <= (z); ++x)
#define per(x, y, z) for (int x = (y); x >= (z); --x)
#define endl '\n'
inline void fast_io() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); }

const int N = 3e7 + 5;
struct IO {
#define mxsz (1 << 21)
	char buf[mxsz], * p1, * p2;
	IO() : p1(buf), p2(buf) {}
	inline char gc() {
		if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, mxsz, stdin);
		return p1 == p2 ? ' ' : *p1++;
	}
	inline int read() {
		int r = 0; char c = gc(); bool rev = 0;
		while (c < '0' || c > '9') rev |= (c == '-'), c = gc();
		while (c >= '0' && c <= '9') r = r * 10 + (c ^ 48), c = gc();
		return rev ? ~r + 1 : r;
	}
} io;
ll a[N];
const int mod = 993244853; //注意模数是993244853,而不是998244353
Modint<mod> res = 0;
Modint<mod> pow131(Modint<mod> n) {
	return Modint<mod>(131) ^ n.val; //快速幂计算 131 的 i 次方
}
int i = 1;
stack<ll> st;
Modint<mod> solve() {
	int n;
	n = io.read();
	Modint<mod> ans = 65537;
	ll maxn = -1, cur = 0; //这里 cur 用来存储a[i-1],因为题目给的是a[i]-a[i-1],差分数组,需要用差加上前一项才能算出当前这一项(这里也可以先把 a 还原再运算)
	rep(i, 1, n) {
		a[i] = io.read();
		a[i] += cur;
		if (maxn > a[i]) { //满足条件则不合法
			ans = 13579; //这里不能直接 return,否则会 WA
		}
		while (!st.empty() && st.top() > a[i]) { //单调栈
			maxn = max(maxn, st.top()); //更新最大值
			st.pop(); 
		}
		st.push(a[i]);
		cur = a[i];
	}
	return ans;
}
int main() {
    fast_io();
	int t;
	t = io.read(); 
	while (t--) {
        while (st.size()) st.pop(); //清空,否则提交两行泪
		res += pow131(i++) * solve(); 
	}
	cout << res;
    return 0;
} //完结撒花

代码中使用了自定义的 Modint 用于快速取模运算,具体请见这里。

复杂度分析

  • 时间复杂度为 O(∑n)\mathcal{O(\sum n)},也可写作 O(t×n)\mathcal{O(t \times n)}。
  • 空间复杂度为 O(n)\mathcal{O(n)}。
原文