hdu_2838_Cow Sorting(树状数组求逆序对)
题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=2838
题意:给你一串数,让你排序,只能交换相邻的数,每次交换花费交换的两个树的和,问最小交换的价值
题解:实质就是求逆序对
1 #include<cstdio> 2 #define F(i,a,b) for(int i=a;i<=b;i++) 3 typedef long long LL; 4 const int N=1e5+7; 5 int num[N],n,x,cnt; 6 LL sum[N],ans; 7 8 inline void add(int x,int k){for(;x<=100000;x+=x&-x)num[x]+=1,sum[x]+=k;} 9 inline int asknum(int x){int an=0;while(x>0)an+=num[x],x-=x&-x;return an;} 10 inline LL asksum(int x){LL an=0;while(x>0)an+=sum[x],x-=x&-x;return an;} 11 12 int main(){ 13 while(~scanf("%d",&n)){ 14 F(i,1,N-1)num[i]=0,sum[i]=0;ans=0; 15 F(i,1,n){ 16 scanf("%d",&x),add(x,x),cnt=i-asknum(x); 17 if(cnt)ans+=(LL)cnt*x+asksum(100000)-asksum(x); 18 } 19 printf("%lld\n",ans); 20 } 21 return 0; 22 }