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).
题意:
有 n 头牛,每头牛有一个脾气值,每交换两头牛的花费是两头牛的脾气值之和,求将牛按脾气值排为升序最少需要多少花费。
思路:
如果一头牛的位置错误,那它正确位置一定也有一头位置错误的牛,以此类推,一定可以将某些位置错误的牛连成一个长度为len的环。于是得出一个子问题,将一些位置全部错误的牛变为升序所需要的最少花费。对于这个问题,可以想到两种情况。
1.用这个环中脾气值最小的牛来作为中介,每次将一头牛位置还原, len-1 次之后所有的牛位置全部正确了,最小的牛用了 len-1 次,其他牛用了 1 次,加起来即为总花费。
2.用环之外的脾气值最小的牛来作为中介,先将环中脾气值最小的牛交换到环外,然后和 1 情况一样处理,最后再将环中脾气值最小的牛交换回来。
代码:
#include"iostream"
#include"cstring"
#include"cstdio"
#include"string"
#include"vector"
#include"cmath"
#include"queue"
#include"map"
#include"set"
#include"algorithm"
#define MAXN 10005
#define lson id<<1
#define rson id<<1|1
#define LL long long
#define INF 0x7f7f7f7f
#define mod 1000000007
const double eps = 1e-10;
const double PI = 2.0*asin(1.0);
using namespace std;
int s1[10005],s2[10005],minn1,minn2;
bool flag[10005];
int main(void)
{
int n;
while(~scanf("%d",&n))
{
memset(flag,false,sizeof(flag));
minn1=1<<30;
for(int i=0;i<n;i++)
{
scanf("%d",&s1[i]);
s2[i]=s1[i];
minn1=min(minn1,s1[i]);
}
sort(s2,s2+n);
int ans=0;
for(int i=0;i<n;i++)
{
if(s1[i]!=s2[i]&&!flag[i])
{
int sum=0;
int len=0;
int now=s1[i];
minn2=s1[i];
while(1)
{
for(int j=0;j<n;j++)
{
if(s2[j]==now&&s2[j]!=s1[j]&&!flag[j])
{
flag[j]=true;
len++;
now=s1[j];
minn2=min(minn2,s1[j]);
sum+=s1[j];
break;
}
}
if(now==s1[i])//找到第一头牛,环已经形成
break;
}
ans+=min((len-2)*minn2+sum,(len+1)*minn1+minn2+sum);
}
}
printf("%d\n",ans);
}
return 0;
}