Description
马达加斯加贞鱼是一种神奇的双脚贞鱼,它们把自己的智慧写在脚上——每只贞鱼的左脚和右脚上个有一个数。有一天,K只贞鱼兴致来潮(1≤k≤10^5),排成一列,从左到右第i只贞鱼会在右脚写Ai(1≤Ai≤10^9),左脚上写上i(1≤i≤K),第二年,这K只贞鱼按右脚的数从小到大排成一列,然后,它们决定重编号,从左到右第i只贞鱼会在右脚上写上左脚的数,在左脚上写i,第三年,它们按第二年的方法重排列、重编号……n年后(1≤n≤10^5),对于从左到右第i和第j贞鱼,若i
#include<cstdio>
#include<algorithm>
#include<cstring>
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
using namespace std;
int n,m;
const int N=1e6+5;
typedef long long ll;
struct node
{
int x,id;
}a[N];
int b[N],tmp[N];
ll ans;
inline void merge_sort(int l,int r)
{
if (l==r)return;
int mid=(l+r)>>1;
int cnt=l,h1=l,h2=mid+1;
merge_sort(l,mid);
merge_sort(mid+1,r);
while (h1<=mid&&h2<=r)
{
while (b[h1]>b[h2])
{
tmp[cnt++]=b[h2];
h2++;
ans+=(mid-h1+1);
if (h2>r)break;
}
tmp[cnt++]=b[h1];
h1++;
}
fo(i,h1,mid)tmp[cnt++]=b[i];
fo(i,h2,r)tmp[cnt++]=b[i];
fo(i,l,r)b[i]=tmp[i];
}
bool cmp(node x,node y)
{
if (x.x==y.x)return x.id<y.id;
else return x.x<y.x;
}
int main()
{
scanf("%d",&n);
fo(i,1,n)
{
scanf("%d",&a[i].x);
a[i].id=i;
}
sort(a+1,a+1+n,cmp);
fo(i,1,n)b[a[i].id]=i;
scanf("%d",&m);
if(m&1)
{
fo(i,1,n)
{
a[i].x=b[i];
a[i].id=i;
}
sort(a+1,a+n+1,cmp);
fo(i,1,n)b[i]=a[i].id;
}
merge_sort(1,n);
printf("%lld\n",ans);
}