hdoj Cow Sorting 2838 (树状数组)

211 篇文章 1 订阅
4 篇文章 0 订阅

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值