题面
样例
6
2
8
4
5
3
6
3
分析
思路见注释。
Code
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <climits>
#define LL long long
using namespace std;
const int MAXN = 3e5 + 5;
void read(int &x) {
x = 0; int f = 1; char c = getchar();
for(; c < '0' || c > '9'; c = getchar()) if(c == '-') f = 0;
for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
x = f ? x : -x;
}
int n, a[MAXN], lsh[MAXN];
LL Bit[MAXN], tmp[MAXN], ans[MAXN], res = 0;
int Lowbit(int x) { return x & (-x); }
void Update(int x) { for(int i = x; i <= 300001; i += Lowbit(i)) Bit[i] ++; }
LL ask(int x) { LL sum_ = 0; for(int i = x; i; i -= Lowbit(i)) sum_ += Bit[i]; return sum_; }
LL Min(LL x, LL y) { return x < y ? x : y; }
// ~~容易~~发现一个性质:最小的一定要放在两边
// 我们放完最小的,就可以把第二小的当做最小的
// 那最小的放在哪边呢,显然是离他最近的那边(因为移完后其他的草相对位置不变)
// 所以对于一棵草,他的贡献为 min(左边比它大的个数,右边比他大的个数)
int main() {
read(n);
for(int i = 1; i <= n; i ++) read(a[i]), ans[i] = 9e18, lsh[i] = a[i];
sort(lsh + 1, lsh + 1 + n);
int len = unique(lsh + 1, lsh + 1 + n) - lsh - 1;
for(int i = 1; i <= n; i ++) a[i] = lower_bound(lsh + 1, lsh + 1 + len, a[i]) - lsh;
for(int i = 1; i <= n; i ++) {
ans[i] = Min(ans[i], i - 1 - ask(a[i])); Update(a[i]);
}
memset(Bit, 0, sizeof(Bit));
for(int i = n; i >= 1; i --) {
ans[i] = Min(ans[i], n - i - ask(a[i])); Update(a[i]);
}
for(int i = 1; i <= n; i ++) res += ans[i];
printf("%lld", res);
return 0;
}