1697: [Usaco2007 feb]cow sorting cattle sort time limit:5 Sec Memory limit:64 MB submit:712 solved:416 [SUBM It][status][discuss] Description
Farmer John is ready to queue his n (1 <= n <= 10,000) cows for action. Because a big-tempered bull could be disruptive, John wanted to sort the cows by the size of their temper. Each cow's temper is an integer between 1 and 100,000 and no two cows have the same temper value. During the sorting process, JOHN can swap the positions of any two cows. Because the big-tempered cows are not moving, John needs x+y seconds to exchange two cows with a temper value of x and Y. Please help John calculate the shortest time to order all the steaks.
Input
Line 1th: A number, N.
Line 2~n+1: One number per line, and line i+1 is the temper value of the first cow.
Output
Line 1th: A number that puts all steaks in good order for the shortest time.
Sample Input3
2
3
1
Input explanation:
There were three cows in the queue, with a temper of 2, 3, and 1.
Sample Output7
Output Explanation:
2 3 1: Initial sequence
2 1 3: Exchange temper for the cattle of 3 and 1 (Time =1+3=4).
1 2 3: Exchange temper for the cattle of 1 and 2 (Time =2+1=3). In order to find out where each cow should be, you can see that the exchanged cows must be in the same permutation cycle, so for each cycle, consider separatelyThere are two ways of doingthe first is that each element and the smallest always changeThe second is to change the smallest of the outside and keep changing it, and finally change it back .two kinds of minimum value.
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Charbuf[10000000], *ptr = BUF-1; inlineintReadint () {intn =0; CharCH = *++ptr; while(Ch <'0'|| CH >'9') ch = *++ptr; while(Ch <='9'&& CH >='0') {n= (n <<1) + (n <<3) + CH-'0'; CH= *++ptr; } returnN;} typedefLong Longll;Const intMAXN =10000+Ten;intNUM[MAXN], POS[MAXN], A[MAXN];BOOLVIS[MAXN] = {false};intMain () {fread (buf,sizeof(Char),sizeof(BUF), stdin); intN =Readint (); for(inti =1; I <= N; i++) Num[i] = a[i] =Readint (); Sort (a+1, A + N +1); for(inti =1; I <= N; i++) Pos[i] = Lower_bound (A +1, A + N +1, Num[i])-A; ll ans=0; for(intJ, Min, tot, siz, i =1; I <= N; i++){ if(Vis[i])Continue; Min= Tot =Num[i]; Siz=1; Vis[i]=true; J=Pos[i]; while(!Vis[j]) {Min=min (min, num[j]); Tot+=Num[j]; Siz++; VIS[J]=true; J=Pos[j]; } ans+ = min (ll) min * (Siz-2), (LL) a[1] * (Siz +1) + Min) +tot; } printf ("%lld\n", ans); return 0;}
[BZOJ1697] [Usaco2007 Feb] Cow Sorting Cattle Sort