题外话:我们未能击穿冒泡排序的装甲(大雾
每当分治开始回溯时,一定是这个数的左右都是分割点,而这也就是说这个数的位置的前面就是,后面是。我们从Out of Sorts G这道题中知道,每个当前位置在其最终位置之前的数每次只会向后移动一个位置,所以定义一个表示的前缀中排序后最靠后的位置,要使得一个位置的前面和正好是的交换次数就是(这样这段全都换好了),注意每个位置至少对答案有的贡献,还有只有一个数时会直接return掉。
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100005;
struct a{long long p,v;}c[N];
long long pos[N],ctr[N];
long long n,ans;
bool cmp(a x,a y)
{
return x.v==y.v?x.p<y.p:x.v<y.v;
}
long long maxx(long long x,long long y)
{
return x>y?x:y;
}
int main ()
{
scanf("%lld",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&c[i].v),c[i].p=i;
if(n==1) {printf("0"); return 0;}
sort(c+1,c+1+n,cmp);
for(int i=1;i<=n;i++)
pos[i]=maxx(pos[i-1],c[i].p),ctr[i]=pos[i]-i;
for(int i=1;i<=n;i++)
ans+=maxx(1ll,maxx(ctr[i],ctr[i-1]));
printf("%lld",ans);
return 0;
}