[POJ 3270] Cow Sorting

本文探讨了如何通过最小化交换奶牛的次数来优化它们按不耐烦程度排序的过程,提供了求解此类问题的方法并给出了具体实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Cow Sorting
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6287 Accepted: 2429

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 2007 February Gold
 
置换群、代码比较丑
#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
#define INF 0x3f3f3f3f
#define N 10010

int n;
int mi;
int b[N];
int vis[N];

struct Node
{
    int ori,now;
}a[N];

int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        mi=INF;
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&a[i].ori);
            mi=min(a[i].ori,mi);
            b[i]=a[i].ori;
        }
        sort(b+1,b+n+1);
        for(int i=1;i<=n;i++)
        {
            a[i].now=lower_bound(b+1,b+n+1,a[i].ori)-b;
        }
        int ans=0;
        int len,sum,t1,t2;
        for(int i=1;i<=n;i++)
        {
            if(a[i].now!=i)
            {
                len=1;
                sum=0;
                while(a[i].now!=i)
                {
                    len++;
                    sum+=a[i].ori;
                    swap(a[i],a[a[i].now]);
                }
                t1=sum+(len-1)*a[i].ori;
                t2=sum+(len-1)*mi+(a[i].ori+mi)*2;
                ans+=min(t1,t2);
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/hate13/p/4430655.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值