Cow sorting
Time Limit: 2000MS |
|
Memory Limit: 65536K |
Total Submissions: 6287 |
|
Accepted: 2429 |
Description
Farmer John ' sN (1≤  N ≤10,000) cows is lined up to being milked in the evening. Each cow have a unique "grumpiness" level in the range 1...100,000. Since Grumpy cows is more likely to damage FJ ' s milking equipment, FJ would like to reorder the cows in line so they is Lined up in increasing order of grumpiness. During This process, the places of any and cows (not necessarily adjacent) can be interchanged. Since Grumpy cows is harder to move, it takes FJ a total of  X + y units of time to exchange, cows whose grumpiness levels Are  X and   Y .
FJ 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
3231
Sample Output
7
Hint
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
Usaco February Gold permutation group, code comparison ugly
#include <iostream>#include<algorithm>#include<cstdio>using namespacestd;#defineINF 0x3f3f3f3f#defineN 10010intN;intmi;intB[n];intVis[n];structnode{intOri,now;} A[n];intMain () { while(SCANF ("%d", &n)! =EOF) {mi=INF; for(intI=1; i<=n;i++) {scanf ("%d",&A[i].ori); Mi=min (a[i].ori,mi); B[i]=A[i].ori; } sort (b+1, b+n+1); for(intI=1; i<=n;i++) {A[i].now=lower_bound (b +1, b+n+1, A[i].ori)-b; } intans=0; intlen,sum,t1,t2; for(intI=1; i<=n;i++) { if(a[i].now!=i) {len=1; Sum=0; while(a[i].now!=i) {len++; Sum+=A[i].ori; Swap (A[i],a[a[i].now]); } T1=sum+ (len-1)*A[i].ori; T2=sum+ (len-1) *mi+ (A[I].ORI+MI) *2; Ans+=min (t1,t2); }} printf ("%d\n", ans); } return 0;}
[POJ 3270] Cow sorting