You are given nn integers wi(i=0,1,...,n−1)wi(i=0,1,...,n−1) to be sorted in ascending order. You can swap two integers wiwi and wjwj. Each swap operation has a cost, which is the sum of the two integers wi+wjwi+wj. You can perform the operations any number of times.
Write a program which reports the minimal total cost to sort the given integers.
Input
In the first line, an integer nn is given. In the second line, nn integers wi(i=0,1,2,...n−1)wi(i=0,1,2,...n−1) separated by space characters are given.
Output
Print the minimal cost in a line.
Constraints
- 1≤n≤1,0001≤n≤1,000
- 0≤wi≤1040≤wi≤104
- wiwi are all different
Sample Input 1
5 1 5 3 4 2
Sample Output 1
7
Sample Input 2
4 4 3 2 1
Sample Output 2
10
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
#define maxx 1010
#define maxn 10010
int C[maxn];
int main(){
int n,ans=0;
int A[maxx],B[maxx];
bool V[maxx];
cin>>n;
for(int i =0;i<n;i++) {
cin>>A[i];
B[i]=A[i];
V[i]=false;
}
sort(B,B+n);
for(int i=0;i<n;i++) C[B[i]]=i;//C数组的value标识A[i]的值在B[i]中的位置,即排序后的正确位置
int x=*min_element(A,A+n);//找出用于外援的最小的值
for(int i=0;i<n;i++){
if(V[i]==true) continue;
int s=0,minn=maxn,c_len=0;
int cur=i;
while(V[cur]==false){
c_len++;//循环的长度
s+=A[cur];
minn=min(minn,A[cur]);//找出min值
V[cur]=true;
cur=C[A[cur]];//循环的下一个元素
}
ans+=min(s+(c_len-2)*minn,s+minn+(c_len+1)*x);
}
cout<<ans<<endl;
return 0;
}