Cow Sorting
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2475 Accepted Submission(s): 801
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).
Source
2009 Multi-University Training Contest 3 - Host by WHU
/*
略感心痛,,,尼玛,,,,,把val用LL型其他用int型一直wa,最后把所有的都换成了LL型才过了。。。
变量定义这么多是为了透彻的理解和应用树状数组,给以后看的时候不要再想那么长时间。
Time:2014-12-22 9:55
*/
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
const int MAX=100000+10;
struct Node{
LL num;
LL val;
}c[MAX];
LL nVal;
LL lowbit(LL x){
return x&(-x);
}
void update(LL pos,LL val){
while(pos<=nVal){
c[pos].num++;
c[pos].val+=val;
pos+=lowbit(pos);
}
return;
}
LL Get_num(LL vpos){//比val小的个数
LL ret=0;
while(vpos){
ret+=c[vpos].num;
vpos-=lowbit(vpos);
}
return ret;
}
LL Get_val(LL vpos){//pos应该范围是0--nVal的范围,比val小的个数的和
LL ret=0;
while(vpos){
ret+=c[vpos].val;
vpos-=lowbit(vpos);
}
return ret;
}
int main(){
LL n;
while(scanf("%lld",&n)!=EOF){
memset(c,0,sizeof(c));
nVal=n;
LL pos;LL ans=0;
for(int i=1;i<=n;i++){
scanf("%lld",&pos);
LL kVal=pos;
update(pos,kVal);
LL sum=i-Get_num(kVal);//前边总共比val小的个数,后来想了想感觉不是很对,,应该是个数还是值?有点困惑
if(sum){
LL v=Get_val(nVal)-Get_val(kVal);//因为前k项中所有的值都比n小,减去前k项中比k小的值的和,就是比k大的值
ans+=(v+sum*kVal);
}
}
printf("%lld\n",ans);
}
return 0;
}