这题要知道最少所需的交换次数就是从后往前开始看,看后面的数有几个比自己小,加上去,再依次往前,就是结果了。
主要用到的技巧除了树状数组就是离散化,因为我们注意到500000个数的范围会达到999999999,太大了,所以我们可以利用结构体标记他们的大小关系,利用结构体来记录他们的大小关系,这样就可以节省很多空间。
#include <stdio.h>
#include <string.h>
#include<algorithm>
using namespace std;
struct node
{
int val;
int pos;
}num[500000+10];
int cmp(node x,node y)
{
return x.val<y.val;
}
int cmp1(node x,node y)
{
return x.pos<y.pos;
}
const int n=500000+10;
__int64 c[n];
int lowbit(int k)
{
return (k&(-k));
}
__int64 sum(int x) //求和
{
__int64 ret = 0;
while(x>0)
{
ret+=c[x];
x-=lowbit(x);
}
return ret;
}
void add(int x,int d) //修改节点的值
{
while(x<=n)
{
c[x]+=d;
x+=lowbit(x);
}
}
int main()
{
int t;
while(~scanf("%d",&t)&&t)
{
int i;
__int64 ans=0;
memset(c,0,sizeof(c));
for(i=0;i<t;i++)
{
scanf("%d",&num[i].val);
num[i].pos=i;
}
sort(num,num+t,cmp);
for(i=0;i<t;i++)
{
num[i].val=i+1;
}
sort(num,num+t,cmp1);
for(i=t-1;i>=0;i--)
{
add(num[i].val,1);
ans+=sum(num[i].val-1);
}
printf("%I64d\n",ans);
}
return 0;
}