水一篇题解。
读者可能没有做过 CF1637H,但是作者在做本题之前做过了,这就够了。
我们考虑最终的排列应当是两个升序子序列拼起来,这个过程和 CF1637H 中选出一个子序列移到开头是完全一样的。又因为交换操作是可逆的,我们直接给排列取逆,然后贺一个 CF1637H 的做法就行了。
#include<bits/stdc++.h>
#define ll long long
#define pii pair<int,int>
#define fi first
#define se second
using namespace std;
int read()
{
int x = 0;
char c = getchar();
while(c < '0' || c > '9')
c = getchar();
while(c >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0',c = getchar();
return x;
}
int n,p[1000005],d[1000005],c[1000005];
void update(int x)
{
while(x <= n)
d[x]++,x += (x & (-x));
}
int query(int x)
{
int ret = 0;
while(x)
ret += d[x],x -= (x & (-x));
return ret;
}
ll sum,ans;
int main()
{
n = read();
for(int i = 1;i <= n;i++)
p[read()] = i;
for(int i = 1;i <= n;i++)
{
int tmp = query(p[i]);
sum += (i - 1 - tmp);
c[i] = (i - 1 - tmp * 2) - (p[i] - 1 - tmp) * 2;
update(p[i]);
}
ans = sum;
sort(c + 1,c + 1 + n,greater<int>());
for(int i = 1;i <= n;i++)
sum -= c[i] + i - 1,ans = min(ans,sum);
printf("%lld\n",ans);
return 0;
}