题解:P17177 Check Check Permutation Clear

· · 题解

题解:P17177 Check Check Permutation Clear

作为我月赛唯一场切的一题,我决定写篇题解纪念一下。

前置芝士:单调栈。

解题思路:

Step 1:

首先我们可以按题目要求模拟,求出原序列 a 后直接暴力计算a 的逆序对个数和单调栈弹栈次数,时间复杂度瓶颈在暴力求逆序对,为 O(tn^2),期望得分 30 分。

Step 2:

注意到数据范围是 \sum n \le 3\times 10^7,加上时限仅 500ms,O(tn^2) 的复杂度显然是过不去的,考虑优化。

实际上求一个序列的逆序对个数是可以用归并排序或树状数组实现 O(n\log n) 的复杂度的(具体请看这里)。所以复杂度可以被优化为 O(tn\log n),期望得分 60 分。

Step 3:

由于 n 过大且时限过小,O(tn\log n) 的复杂度显然还是不够优秀。我们继续观察,设 inv 表示逆序对个数,c 表示单调栈弹栈次数。研究一下样例可以发现,任意一个序列都必然满足 inv \ge c(证明不难,可用反证法)。观察到这个性质后这题就差不多了,对于第 i 位,我们维护在第 i 位入栈之前的已经被弹出单调栈的数的最大值,设这个最大值为 maxa,则有两种情况:

这样我们就优化掉了求逆序对的复杂度,时间复杂度为 O(tn),期望得分 100 分。

AC Code:

#include <iostream>
#include <algorithm>
#include <cstring>
#define ll long long
using namespace std;
const int mod = 993244853;
const int N = 3e7 + 5;
int T, n, a[N], b[N], top;
ll ans[N], Ans;

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;

inline void write(ll x){
    if(x < 0) putchar('-'), x = -x;
    if(x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

void solve(int I){
    top = 0;
    n = io.read();
    for(int i = 1, t; i <= n; ++i){
        t = io.read();
        a[i] = t + a[i - 1];
    }
    int maxx = 0;
    for(int i = 1; i <= n; ++i){
        int tmp = maxx;
        if(maxx > a[i]){
            ans[I] = 13579;
            return;
        }
        while(top && a[b[top]] > a[i]){
            tmp = max(tmp, a[b[top]]);
            --top;
        }
        maxx = tmp;
        b[++top] = i;
    }
    ans[I] = 65537;
}

ll qpow(ll a, ll b){
    ll res = 1;
    while(b){
        if(b & 1) res = res * a % mod;
        a = a * a % mod;
        b >>= 1;
    }
    return res % mod;
}

int main(){
    T = io.read();
    for(int i = 1; i <= T; ++i) solve(i);
    for(int i = 1; i <= T; ++i) Ans = (Ans + qpow(131, i) % mod * ans[i] % mod) % mod;
    cout << Ans << '\n';
    return 0;
}
/*
input:
2
8 1 3 1 1 -4 5 1 -5
7 1 2 1 1 -3 4 1

output:
133214453
*/