TOJ 1690 Cow Sorting (置换群)

时间:2021-01-07 11:18:58

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

Line 1: A single integer: N.
Lines 2..N+1: Each line contains a single integer: line i+1 describes the grumpiness of cow i.

Output

Line 1: A single line with the minimal time required to reorder the cows in increasing order of grumpiness.

Sample Input

3
2
3
1

Sample Output

7

Hint

2 3 1 : Initial order.
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).

Source

USACO February 2007

 #include <stdio.h>
#include <iostream>
#define inf 0x3f3f3f3f
#define MAXN 110000
using namespace std; int n;
int a[MAXN];
int pos[MAXN];
int use[MAXN]; int main(int argc, char *argv[])
{
int maxValue;
int minValue;
while( scanf("%d" ,&n)!=EOF ){
maxValue=;
minValue=inf;
memset(pos , ,sizeof(pos));
memset(use , ,sizeof(use));
for(int i=; i<=n; i++){
scanf("%d",&a[i]);
pos[a[i]]++;
if(a[i]>maxValue){
maxValue=a[i];
}
if(a[i]<minValue){
minValue=a[i];
}
}
for(int i=; i<=maxValue; i++){
pos[i]=pos[i-]+pos[i];
}
int sum=;
for(int i=; i<=n; i++){
//找循环节
if(!use[i]){
int j=i;
int len=;
int t=a[j];
int ts=;
while(!use[j]){
//找到置换群里最小的数
if(a[j]<t){
t=a[j];
}
//求置换群的和
ts+=a[j];
use[j]=;
j=pos[a[j]];
len++;
}
if(<len){
sum+=ts;
}
if(<len){
int t1=(len-)*t;
int t2=t+(len+)*minValue;
if(t1<t2){
sum+=t1;
}
else{
sum+=t2;
}
}
}
}
printf("%d\n",sum);
}
return ;
}