# POJ 3270 Cow Sorting （置换群）

## 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.

## 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


## AC 代码

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<iostream>
using namespace std;
#include<queue>
#include<map>
#define INF (1<<25)

int a[11000];
int b[11000];
bool vis[110000];
int main()
{
int n;
while(cin>>n)
{
memset(vis,false,sizeof(vis));
map<int,int>mapp;           // n元置换群映射
int ksmin=INF;
for(int i=0; i<n; i++)
{
scanf("%d",a+i);
ksmin=min(ksmin,a[i]);  // 找出所有牛的最小愤怒值
}
memcpy(b,a,sizeof(int)*n);
sort(b,b+n);
for(int i=0; i<n; i++)      // 建立映射关系
mapp[a[i]]=b[i];
int ans=0;
for(int i=0; i<n; i++)
{
if(!vis[a[i]])          // 遍历每个轮换
{
int p=a[i],sum=0,minn=a[i],len=0;   // 记录和与长度以及轮换中最小值
while(!vis[p])
{
sum+=p;
++len;
minn=min(minn,p);
vis[p]=true;
p=mapp[p];
}
ans+=min(sum-minn+(len-1)*minn,sum+minn+(len+1)*ksmin);
}
}
cout<<ans<<endl;
}
return 0;
}