Cow Sorting POJ - 3270 (置换)

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

一个置换的题,上次多校遇到过,这次又遇到了,所幸之前学过polya,对置换不算太陌生,上次只是试探性的交了一发,1A,牛逼坏了哈哈,不过单纯性的考置换的题真的是第一次遇到,之前做polya的时候,有一种很神奇的方法用gcd求的置换的循环的个数(其实就是置换的幂运算),但是这次的题还需要置换的大小,上次多校幸好还是想出了计算方法,其实也不难,同理也适用这道题。。。

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iostream>
using namespace std;
struct node
{
    int val;
    int index;
}p[10005];
int cmp(node x1,node x2)
{
    return x1.val<x2.val;
}
int a[10005];
bool vis[10005];
int n;
int main()
{
    scanf("%d",&n);
    int x;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&x);
        p[i].val=x;
        p[i].index=i;
    }
    sort(p+1,p+1+n,cmp);
    for(int i=1;i<=n;i++)
    {
        a[p[i].index]=i;
    }

    long long ans=0;
    int countt=1;
    vis[1]=true;
    int res=p[1].val;
    int temp=a[1];
    while(!vis[temp])
    {
        countt++;
        res+=p[temp].val;
        vis[temp]=true;
        temp=a[temp];
    }
    //cout<<res<<endl;
    if(countt>1)
        ans=res+p[1].val*(countt-2);
    int minn=p[1].val;
    for(int i=1;i<=n;i++)
    {
        if(vis[i])
            continue;
        vis[i]=true;
        res=p[i].val;
        countt=1;
        temp=a[i];
        while(!vis[temp])
        {
            countt++;
            vis[temp]=true;
            res+=p[temp].val;
            temp=a[temp];
        }
        if(countt>1)
            ans+=min(res+p[i].val*(countt-2),2*(p[i].val+minn)+res-p[i].val+minn+minn*(countt-2));

    }

    printf("%lld\n",ans);
    return 0;
}

poj暂时交不了题,暂时先贴一下代码。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值