题解:P16996 【MX-S15-T2】「DLESS-5」宇宙射线

· · 题解

感觉就是乱做,模了一堆样例最后就能做出来了。

因为只会恰好错误一次,假设当外层循环枚举到 i 的时候出错,则 i+1\sim n 的序列一定恰好是 i+1\sim n,且剩下的排序不会出错,因此 1\sim i-1 也会排好序。

因此可以枚举 i,并记录最终的序列 a_i 有多少种不同的错误取值,累加到答案里面即可。

假设外层循环枚举到了 t,n-t+1 的位置在 p,分类讨论 a_j 最终能否填到 a_{n-t+1}。

第二类的取值是 O(1) 的,第一类取值可以维护一个后缀的单调栈,注意可能有最终排列依旧有序的情况,只要出现一次 p>2 的情况就能做到。于是得到了一份 O(n^2) 的代码,可以获得 52 分。

#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, a[N], flag;
long long ans;
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i < n; i++) {
        int pos = -1;
        for (int j = n - i + 1; j >= 1; j--) {
            if (a[j] == n - i + 1) {
                pos = j;
                break;
            }
        }
        if (pos > 2) flag = 1;
        int mx = -1;
        for (int j = n - i + 1; j > pos; j--) {
            if(a[j] > mx) ans++, mx = a[j];
        }
        if (mx != n - i) ans++;
        for (int j = 1; j <= n - i; j++) {
            if (a[j] > a[j + 1]) swap(a[j], a[j + 1]);
        }
    }
    if (flag) ans++;
    cout << ans << '\n';
    return 0;
}

考虑优化,经过手摸,不难发现在进行冒泡排序的同时维护后缀 1\sim n-t+1 的单调栈有一些非常好的性质。

首先,每次取走的一定是单调栈的栈顶元素,即 n-t+1,考虑取走他后单调栈的变化。

单调栈中的其他元素在冒泡排序过程中相对位置不会发生变化,非单调栈的元素也不关心,第一二类贡献很好计算,就能做到 O(n) 了。

#include <bits/stdc++.h>
using namespace std;
const int N = 2e6 + 10;
int n, a[N], b[N], c[N], t;
long long ans;
bool check() {
    for (int i = n; i >= 2; i--) {
        if(b[i] == i) continue;
        else if(b[i - 1] == i) b[i - 1] = b[i];
        else return 1;
    }
    return 0;
}
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        b[n - i + 1] = a[i];
    }
    for (int i = n; i >= 1; i--) {
        if (a[i] > c[t]) c[++t] = a[i];
    }
    for (int i = 1; i < n; i++) {
        ans += t - 1;
        if (t > 1 && c[t - 1] == c[t] - 1) t--;
        else c[t]--, ans++;  
    }
    if (check()) ans++;
    cout << ans << '\n';
    return 0;
}