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).
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;//头文件
int b[100010],d[100010];
int i;
int a;
int siv[100010];
int c[100010],min;
int diaoyong()
{
int sum=0;
memset(siv,0,sizeof(siv));//初始化,清零
for(i=0;i<a;i++)//对于数组中的数据,一个一个接入
{
if(siv[i])//如果,已经标记,会跳过,接着执行下一个数据
continue;
int t=i;
int s=0;
int first=b[i];
int min=100000000;
while(1)//查找一个独立的循环
{
siv[t]=1;
sum+=b[t];//叠加的循环中的所有值
if(min>b[t])
min=b[t];//挑选出循环的最小值
s++;
if(first==d[t])//跳出循环
break;
t=c[d[t]];
}
if(min*(s-2)>min+(s+1)*d[0])//两种方法的大小判定。
sum=sum+min+(s+1)*d[0];
else
sum=sum+min*(s-2);
}
return sum;
}
int main()
{
while(~scanf("%d",&a))
{
for(i=0;i<a;i++)
{
scanf("%d",&b[i]);//接受原本输入的数据。
c[b[i]]=i;//存储数据原来的位置,便于找到一个独立循环。
d[i]=b[i];//用新的数组接受,便于等会的排序
}
sort(d,d+a);//将d数组变化成我们需要的状态。
printf("%d\n",diaoyong());//调用无输入,又返回。
}
return 0;
}