0
点赞
收藏
分享

微信扫一扫

hdoj Cow Sorting 2838 (树状数组)


Cow Sorting


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2820    Accepted Submission(s): 929



Problem Description


Sherlock's N (1 ≤ N ≤ 100,000) cows are lined up to be milked in the evening. Each cow has a unique "grumpiness" level in the range 1...100,000. Since grumpy cows are more likely to damage Sherlock's milking equipment, Sherlock would like to reorder the cows in line so they are lined up in increasing order of grumpiness. During this process, the places of any two cows (necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes Sherlock a total of X + Y units of time to exchange two cows whose grumpiness levels are X and Y.

Please help Sherlock calculate the minimal time required to reorder the cows.




Input


Line 1: A single integer: N
Lines 2..N + 1: Each line contains a single integer: line i + 1 describes the grumpiness of cow i.




Output


Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.




Sample Input


3 2 3 1




Sample Output


Hint


#include<stdio.h>
#include<string.h>
#define N 100010
#define ll __int64
int n;
struct zz
{
	int cnt;
	ll sum;
}q[N<<2];
ll lobit(int x)
{
	return x&(-x);
}
int update(int gen,int v)
{
	while(gen<=n)
	{
		q[gen].sum+=v;
		q[gen].cnt+=1;
		gen+=lobit(gen);
	}
	return 0;
}
int query(int gen)//返回x前面比x小的元素的个数 
{
	int ans=0;
	while(gen>0)
	{
		ans+=q[gen].cnt;
		gen-=lobit(gen);
	}
	return ans;
}
ll querys(int gen)//返回x前面所有数的和 
{
	ll ans=0;
	while(gen>0)
	{
		ans+=q[gen].sum;
		gen-=lobit(gen);
	}
	return ans;
}
int main()
{	
	int i,x;
	while(scanf("%d",&n)!=EOF)
	{	
		ll ans=0;
		memset(q,0,sizeof(q));
		for(i=1;i<=n;i++)
		{
			scanf("%d",&x);
			update(x,x);
			ll k=i-query(x);//k表示有多少个数是逆序的 
			if(k!=0)
			{
				ll kk=querys(n)-querys(x);//前n个数之和减去比x大的数即为所求。 
				ans+=k*x+kk;
			}
		}
		printf("%I64d\n",ans);
	}
	return 0;
}



举报

相关推荐

0 条评论