题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2838点击打开链接
Cow Sorting
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3522 Accepted Submission(s): 1222
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.
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.
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
7HintInput 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).
题意:树状数组 用两个数组分别储存 逆序的个数 和 比nn大的数的和 因为每次需要两个都移动 因此逆序个数×nn花费固定 加上比nn大的数的和 结果就为所求
此题long long 过不了 用__int 64
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include<algorithm>
#include <math.h>
#include <string.h>
#include <limits.h>
#include <string>
#include <queue>
#include <stack>
#include <set>
#include <vector>
using namespace std;
__int64 tree[111111];
__int64 value[111111];
__int64 lowbit(__int64 x)
{
return x&-x;
}
__int64 getsumtree(__int64 x)
{
__int64 s=0;
while(x>0)
{
s+=tree[x];
x-=lowbit(x);
}
return s;
}
__int64 getsumvalue(__int64 x)
{
__int64 s=0;
while(x>0)
{
s+=value[x];
x-=lowbit(x);
}
return s;
}
void add(__int64 x,__int64 num,__int64 val)
{
while(x<=100000)
{
value[x]+=val;
tree[x]+=num;
x+=lowbit(x);
}
}
int main()
{
__int64 n=0;__int64 sum=0;
scanf("%d",&n);
for(__int64 i=1;i<=n;i++)
{
__int64 nn=0;
scanf("%I64d",&nn);
add(nn,1,nn);
sum+=(getsumtree(n)-getsumtree(nn))*nn+(getsumvalue(n)-getsumvalue(nn));
}
printf("%I64d\n",sum);
}