A - Cow Sorting

A - Cow Sorting
Time Limit:2000MS    Memory Limit:65536KB    64bit IO Format:%I64d & %I64u

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).     
提示:本题目的意思为将一组无序数据转化成有序从小到大数列。并且,
每一步只能交换两个数据,每一步付出的代价就是两个数据之和。
题目看似杂乱无章,其实倒有规律可循。
本题目讨论可分成两种情况
例1: 3 5 1 6 7 8 最终要获得是1 3 5 6 7 8
这数列可以分成两个循环链( 3 5 1)(6 7 8)
而交换的最小情况就是每个数都与最小的交换
所以一次循环得到的值为:(t-2)*min+sum;
例2:1 8 6 7,我们很清楚的看到,如果再用例1的方法解决问题是就比较大了
所以我们也可以选择其他循环群的最小值和这里面的数进行交换,最后在换回来
所以一次循环得到的值就是min1+min*(t+1)+sum;
代码实现就如下面:


<span style="font-size:24px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a,i;
    int asoc[100010],soc[100010];
    int sd[100010],vis[100001];
int main()
{

 int min=1<<25;
    scanf("%d",&a);
    for(i=0;i<a;i++)
    {
        scanf("%d",&soc[i]);
        asoc[i]=soc[i];
        if(soc[i]<min)
        min=soc[i];
        sd[soc[i]]=i;
    }
    sort(asoc,asoc+a);//调整成正确的队列便于比较
    int length=a;
    memset(vis,0,sizeof(vis));
    int ans=0;
    while(length)
    {
        int sum=0;
        int t=0;
        int i=0;
        int mmm=1<<25;//定义最小值
        while(vis[i])i++;
        int beg=i;
        while(1!=0)
        {
            t++;
            vis[i]=1;
            if(soc[i]<mmm)
            mmm=soc[i];
            sum+=soc[i];
            i=sd[asoc[i]];

            if(i==beg)
            break;
        }
        length=length-t;
        if(t==1)
        continue;
        int v1=(t-2)*mmm;
        int v2=mmm+(t+1)*min;
        ans+=(v1<v2)?v1:v2;
        ans+=sum;
    }
    printf("%d\n",ans);
    return 0;

}
</span>


   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值