Description
Farmer John's N (1 ≤ N ≤ 10,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 FJ's milking equipment, FJ 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 (not necessarily adjacent) can be interchanged. Since grumpy cows are harder to move, it takes FJ a total of X+Y units of time to exchange two cows whose grumpiness levels are X and Y.
Please help FJ calculate the minimal time required to reorder the cows.
Input
Lines 2.. N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow i.
Output
Sample Input
3
2
3
1
Sample Output
7
Hint
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).
<span style="font-size:24px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a,i;
int asoc[100010],soc[100010];
int sd[100010],vis[100001];
int main()
{
int min=1<<25;
scanf("%d",&a);
for(i=0;i<a;i++)
{
scanf("%d",&soc[i]);
asoc[i]=soc[i];
if(soc[i]<min)
min=soc[i];
sd[soc[i]]=i;
}
sort(asoc,asoc+a);//调整成正确的队列便于比较
int length=a;
memset(vis,0,sizeof(vis));
int ans=0;
while(length)
{
int sum=0;
int t=0;
int i=0;
int mmm=1<<25;//定义最小值
while(vis[i])i++;
int beg=i;
while(1!=0)
{
t++;
vis[i]=1;
if(soc[i]<mmm)
mmm=soc[i];
sum+=soc[i];
i=sd[asoc[i]];
if(i==beg)
break;
}
length=length-t;
if(t==1)
continue;
int v1=(t-2)*mmm;
int v2=mmm+(t+1)*min;
ans+=(v1<v2)?v1:v2;
ans+=sum;
}
printf("%d\n",ans);
return 0;
}
</span>