UVa 10570 Meeting with Aliens(思路)

该博客主要介绍了UVA 10570题目的解决思路,问题涉及环状序列的优化排列。通过枚举1在序列中的位置,并考虑顺时针和逆时针排列,计算达到1-n顺序所需的最小交换次数。

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

题目链接:http://vjudge.net/problem/UVA-10570


大意:给你一个由1-n组成的环状序列,每次可以交换任意两个数,用最少的交换次数将其变为1-n的环状排列。


思路:可以直接枚举1所在的位置,对于每个位置,排列有顺时针排列和逆时针排列,分别计算一下即可。详见代码


#include<cstdio>
#include<cstring>
#include<iostream>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lc rt<<1
#define rc rt<<1|1
using namespace std;
typedef long long LL;
const int INF = 1e9 + 10;
const int maxn = 500 + 10;
int pos[maxn],arr[maxn],l[maxn],r[maxn],a[maxn],pos_a[maxn];
int n;

int solve_L(int p)
{
    int ans = 0;
    if (a[p] != 1) { //要将位置p置为1
        int x = a[p];
        swap(a[p], a[pos_a[1]]);
        swap(pos_a[x], pos_a[1]);
        ++ans;
    }
    int cur = 1;
    while(cur < n) {
        if (a[l[p]] != 1+cur) {
            int x = a[l[p]];
            swap(a[l[p]], a[pos_a[cur+1]]);
            swap(pos_a[x],pos_a[cur+1]);
            ++ans;
        }
        p = l[p];
        ++cur;
    }
    return ans;
}

int solve_R(int p)
{
    int ans = 0;
    if (a[p] != 1) {
        int x = a[p];
        swap(a[p], a[pos_a[1]]);
        swap(pos_a[x], pos_a[1]);
        ++ans;
    }
    int cur = 1;
    while(cur < n) {
        if (a[r[p]] != 1+cur) {
            int x = a[r[p]];
            swap(a[r[p]], a[pos_a[cur+1]]);
            swap(pos_a[x],pos_a[cur+1]);
            ++ans;
        }
        p = r[p];
        ++cur;
    }
    return ans;
}

int main()
{
    while(scanf("%d",&n) && n) {
        for(int i = 0; i < n; i++) {
            scanf("%d",arr+i);
            pos[arr[i]] = i;
            r[i] = (i+1) % n;
            l[i] = (i-1+n) % n;
        }
        int ans = INF;
        for(int i = 0; i < n; i++) { //枚举1的位置
            memcpy(a, arr, sizeof arr);
            memcpy(pos_a, pos, sizeof pos);
            ans = min(ans, solve_L(i)); //逆时针排列

            memcpy(a, arr, sizeof arr);
            memcpy(pos_a, pos, sizeof pos);
            ans = min(ans, solve_R(i)); //顺时针排列
        }
        printf("%d\n",ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值