我们不难发现,第一次操作之后序列就会变成一段上升,然后突然降下来,再不断上升的一个序列,然后序列每次就只能交换相邻两个错位的数,然后就成了统计逆序对的裸题。
#include<cstdio>
#include<algorithm>
#define LL long long
#define maxn 210000
using namespace std;
int n;
int a[maxn];
int b[maxn];
LL ans;
LL ret[maxn];
void reverse()
{
int i,j,last=1;
for(i=2;i<=n;i++)
if(a[i]>a[i-1])
{
if(i>last+1) ans++;
for(j=last;j<i;j++)
b[j]=a[i-1-j+last];
last=i;
}
if(last<n) ans++; for(j=last;j<=n;j++) b[j]=a[n-j+last];
}
LL get(int x)
{
LL ans=0;
while(x)
{
ans+=ret[x];
x-=(x&-x);
}
return ans;
}
void change(int x)
{
while(x<=n)
{
ret[x]++;
x+=(x&-x);
}
}
int main()
{
int i;
scanf("%d",&n);
for(i=1;i<=n;i++) scanf("%d",&a[i]);
reverse();
for(i=1;i<=n;i++)
{
ans+=i-get(b[i])-1;
change(b[i]);
}
printf("%lld",ans);
return 0;
}