184人阅读 评论(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.

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

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：277820次
• 积分：13474
• 等级：
• 排名：第1023名
• 原创：1116篇
• 转载：20篇
• 译文：0篇
• 评论：23条
阅读排行
最新评论