Minimum Cost Sort Aizu - ALDS1_6_D

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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值