POJ 3270 Cow Sorting(置换群)

本文介绍了一种通过交换元素实现排序的算法,旨在寻找最优交换方案以达到递增序列,同时确保总花费最小。该算法利用置换群的概念,通过两种策略(置换群内部最小交换和与序列最小值交换)来降低总成本。

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

题意:每次交换两数,花费为两数和。最后得到递增序列。求最小花费。

思路:找到所有置换群。两种方法,和置换群里最小的交换或和整个数列最小的交换。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
using namespace std;

typedef long long LL;
#define mem(a, n) memset(a, n, sizeof(a))
#define ALL(v) v.begin(), v.end()
#define si(a) scanf("%d", &a)
#define sii(a, b) scanf("%d%d", &a, &b)
#define siii(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define pb push_back
#define eps 1e-8
const int inf = 0x3f3f3f3f, N = 1e4 + 5, MOD = 1e9 + 7;

int T, cas = 0;
int n, m, k;
bool vis[N];
struct node {
	int num, id;
} a[N];
bool cmp(node a, node b) { return a.num < b.num; }

int main(){
#ifdef LOCAL
    freopen("/Users/apple/input.txt", "r", stdin);
//	freopen("/Users/apple/out.txt", "w", stdout);
#endif
	
    while(si(n) != EOF) {
	    for(int i = 1; i <= n; i ++) si(a[i].num), a[i].id = i;
	    sort(a + 1, a + 1 + n, cmp);
		k = a[1].num;
		mem(vis, 0);
		int ans = 0;
		for(int i = 1; i <= n; i ++) {
			int cnt = 0, idx = i, mi = inf, sum = 0;
			while(vis[idx] == 0) {
				vis[idx] = 1;
				cnt ++;
				mi = min(mi, a[idx].num);
				sum += a[idx].num;
				idx = a[idx].id;
			}
			if(sum) ans += min(sum + (cnt - 2) * mi, sum + mi + (cnt + 1) * k);
		}
		printf("%d\n", ans);
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值