Cow Sorting
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2224 Accepted Submission(s): 701
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
1 #include2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 using namespace std; 9 #define ll long long10 typedef struct abcd11 {12 ll sum,n;13 } abcd;14 abcd a[110000];15 ll lowbit(ll x)16 {17 return x&(-x);18 }19 ll update(ll x)20 {21 int y=x;22 while(x<110000)23 {24 a[x].n++;25 a[x].sum+=y;26 x+=lowbit(x);27 }28 }29 ll fun(ll x)30 {31 ll ans=0;32 while(x>0)33 {34 ans+=a[x].n;35 x-=lowbit(x);36 }37 return ans;38 }39 ll fun1(ll x)40 {41 ll ans=0;42 while(x>0)43 {44 ans+=a[x].sum;45 x-=lowbit(x);46 }47 return ans;48 }49 int main()50 {51 ll n,i,x,ans,z,sum;52 while(~scanf("%I64d",&n))53 {54 memset(a,0,sizeof(a));55 sum=ans=0;56 for(i=0; i