题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2838
Cow Sorting
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 ll __int64
ll c[+],v[+];
int n;
int Lowbit(int k)
{
return (k&-k);
}
void update(int pos,int num,int val)
{
while(pos<=n)
{
c[pos]+=num;
v[pos]+=val;
pos+=Lowbit(pos);
}
}
ll sum_count(int pos)
{
ll s=; while(pos>)
{
s+=c[pos];
pos-=Lowbit(pos);
}
return s;
}
ll sum(int pos)
{
ll s=; while(pos>)
{
s+=v[pos];
pos-=Lowbit(pos);
}
return s;
}
int main()
{
int i,x;
while(scanf("%d",&n)!=-)
{
memset(c,,sizeof(c));
memset(v,,sizeof(v));
ll ans=,k2,k1;
for(i=;i<=n;i++)
{
scanf("%d",&x);
update(x,,x);
k1=i-sum_count(x);///到此为止 比x大的个数;
/*sum_count[x] 为输入i个数的时候 x之前有sum_count[x]个比x小的数 用i相减则为大于x的个数*/
if(k1!=)
{
k2=sum(n)-sum(x);///到此为止 比x大的数的和;
ans+=x*k1+k2;///到此为止 比x大的数与x交换之后的和;
}
}
printf("%I64d\n",ans);
}
return ;
}
/*坑爹的题 必须用 __int64 不能用long long 不能用int ╮(╯▽╰)╭*/