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).
—————————————————————————————————after connecting each point to his target point, we find that it forms a ring .so if you trade in the ring, because you can only make one in place at a time, at least the ring size (k)-1 timesthen we use the minimum MN in the ring to exchange the necessary optimalof course, it could be a point outside the ring for better. This time he's going to swap in and swap out two more operationsjust calculate the cost and try to minimize it.
#include <cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intm=10007;intRead () {intans=0, f=1, c=GetChar (); while(c<'0'|| C>'9'){if(c=='-') f=-1; C=GetChar ();} while(c>='0'&&c<='9') {ans=ans*Ten+ (C-'0'); C=GetChar ();} returnans*F;}intN,v[m],s[m],vis[m],ans;voidminsint&x,intY) {if(y<x) x=y;}intMinintXintY) {returnX<y?x:y;}intMain () {n=read (); for(intI=1; i<=n;i++) v[i]=s[i]=read (); Sort (S+1, s+1+N); for(intI=1; i<=n;i++)if(!Vis[i]) { intMn=v[i],sum=v[i],now=i,h=1; while(1) {Vis[now=lower_bound (s+1, s+1+n,v[now])-s]=1; if(now==i) Break; H++; mins (Mn,v[now]); Sum+=V[now]; } ans=ans+min ((SUM-MN) + (H-1) *mn, (s[1]+MN) *2+ (SUM-MN) + (H-1) *s[1]); }printf ("%d\n", ans); return 0;}View Code
Bzoj 1697: [Usaco2007 feb]cow sorting cattle Sort