UVA 1016 - Silly Sort 置换分解 贪心

                                       Silly Sort

Your younger brother has an assignment and needs some help. His teacher gave him a sequence of
numbers to be sorted in ascending order. During the sorting process, the places of two numbers can be
interchanged. Each interchange has a cost, which is the sum of the two numbers involved.
You must write a program that determines the minimal cost to sort the sequence of numbers.
Input
The input file contains several test cases. Each test case consists of two lines. The first line contains
a single integer n (n > 1), representing the number of items to be sorted. The second line contains n
different integers (each positive and less than 1000), which are the numbers to be sorted.
The input is terminated by a zero on a line by itself.
Output
For each test case, the output is a single line containing the test case number and the minimal cost of
sorting the numbers in the test case.
Place a blank line after the output of each test case
Sample Input
3
3 2 1
4
8 1 2 4
5
1 8 9 7 6
6
8 4 5 3 2 7
0
Sample Output
Case 1: 4
Case 2: 17
Case 3: 41
Case 4: 34

题意:

给定一个序列,数字都不同,每次可以交换两个数字,交换的代价为两数之和,要求出把这个序列变成递增最小代价

题解:

利用置换的分解原理,可以把序列的每条循环单独考虑,对于每条循环而言,不断交换肯定每个数字至少会换到一次,再利用贪心的思想,如果每次拿循环中的最小值去置换,那么就是这个最小值会用长度-1次,而剩下的数字各一次,注意这里还有一种可能优的方法,就是先把整个序列中的最小值换到该循环中,等置换完再换出去,两种都考虑进来即可

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std ;
typedef long long ll;
const int N=5500;
const int inf = 899999;
int main() {
    int a[N],b[N],id[N],n,mi, cas = 0;
    while(~scanf("%d",&n)) {
        if(!n) break;
        mi = inf;
        for(int i = 1; i <= n; i++) {
            scanf("%d",&a[i]);
            mi = min(mi,a[i]);
            b[i] = a[i];
        }
        sort(b + 1, b + n +1);
        for(int i = 1; i <= n; i++) id[b[i]] = i;
        int ans = 0;
        for(int i = 1; i <= n; i++) {
            if(a[i]) {
                int cnt = 0;
                int sum = a[i];
                int now = id[a[i]];
                int tmp = a[i];
                a[i] = 0;
                while(a[now]) {
                    cnt++;
                    sum += a[now];
                    tmp = min (tmp,a[now]);
                    int last = now;
                    now = id[a[now]];
                    a[last] = 0;
                }
                ans += min(tmp * (cnt - 1) + sum, mi * cnt + sum + 2 * (tmp + mi) - tmp);
            }
        }
        printf("Case %d: %d\n\n", ++cas, ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zxhl/p/5143470.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值