题目链接: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;
}