题解:P16996 【MX-S15-T2】「DLESS-5」宇宙射线
感觉就是乱做,模了一堆样例最后就能做出来了。
因为只会恰好错误一次,假设当外层循环枚举到
因此可以枚举
假设外层循环枚举到了
-
若
j>p :当a_p 被交换到a_{j-1} 时出现错误,a_j 继续向后交换,如果能交换到a_{n-t+1} 即符合条件,所以a_j 必须是a_{j\sim n-t+1} 的最大值。 -
若
j<p :当a_j 如果能交换到a_p ,必须大于a_{1\sim p-1} 的所有值才能和a_p 比较,比较错误,a_j 继续向后交换,必须大于a_{p+1\sim n-t+1} 。换句话说,此时只有a_j=n-t 符合条件。
第二类的取值是
#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;
}
考虑优化,经过手摸,不难发现在进行冒泡排序的同时维护后缀
首先,每次取走的一定是单调栈的栈顶元素,即
-
若是
n-t 在n-t+1 之前的位置,则n-t 会顶替n-t+1 。 -
若是
n-t 在n-t+1 之后,则其一定在栈顶下一个位置,直接弹出栈顶。
单调栈中的其他元素在冒泡排序过程中相对位置不会发生变化,非单调栈的元素也不关心,第一二类贡献很好计算,就能做到
#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;
}