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
7
Hint
Input Details Three cows are standing in line with respective grumpiness levels 2, 3, and 1. Output Details 2 3 1 : Initial order. 2 1 3 : After interchanging cows with grumpiness 3 and 1 (time=1+3=4). 1 2 3 : After interchanging cows with grumpiness 1 and 2 (time=2+1=3).
 
#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;
}

阅读更多
个人分类: 好题 hdoj 树状数组
上一篇hdoj Sort it 2689 (归并排序)
下一篇poj Squares 2002 (STL&amp;&amp;枚举+转换) 统计正方形的个数
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭