POJ - 3270 Cow Sorting 置换

本文介绍了一种通过交换元素实现升序排序的方法,并给出了具体的算法思路和实现代码。该算法的目标是在排序过程中找到使得交换代价最小化的方案。

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

题目:有一串数字,要将它排列成升序,每次可以交换两个数,交换一次的代价为两数之和,求代价最小是多少。

思路:置换。对于每个循环,要么是用当前循环内最小的数mi去和其他数交换,要么是用全局最小值MIN和mi交换,然后用MIN去和循环内其他的数进行交换,然后MIN再和mi去交换。

假设循环长度为cnt,循环内所有数的和为sum,那么答案就是sum+min((cnt-2)*mi,mi+(cnt+1)*MIN)。

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<ctime>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f

const int maxn=1e4+50;
int arr[maxn],Hash[maxn],vis[maxn];
int main(){

    int n,MIN;
    while(~scanf("%d",&n)){
        MIN=1000000;
        for(int i=1;i<=n;i++){
            scanf("%d",&arr[i]);
            Hash[i]=arr[i];
            MIN=min(MIN,arr[i]);
        }
        sort(Hash+1,Hash+n+1);
        for(int i=1;i<=n;i++)
            arr[i]=lower_bound(Hash+1,Hash+n+1,arr[i])-Hash;
        mm(vis,0);
        int ans=0;
        for(int i=1;i<=n;i++){
            if(vis[i]) continue;
            int cnt=0,pos=i,mi=Hash[i];
            while(vis[pos]==0){
                ans+=Hash[pos];
                mi=min(mi,Hash[pos]);
                vis[pos]=1;
                cnt++;
                pos=arr[pos];
            }
//            printf("%d %d %d %d\n",MIN,mi,cnt,ans);
            ans=ans+min((cnt-2)*mi,mi+(cnt+1)*MIN);
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值