UVA10570-Meeting with Aliens(枚举)

时间:2022-08-03 04:48:13
Problem UVA1616-Caravan Robbers

Accept: 531  Submit: 2490
Time Limit: 3000 mSec

UVA10570-Meeting with Aliens(枚举) Problem Description

UVA10570-Meeting with Aliens(枚举)

Input

Input will start with a positive integer, N (3 ≤ N ≤ 500) the number of aliens. In next few lines there will be N distinct integers from 1 to N indicating the current ordering of aliens. Input is terminated by a case where N = 0. This case should not be processed. There will be not more than 100 datasets.

UVA10570-Meeting with Aliens(枚举) Output

For each set of input print the minimum exchange operations required to fix the ordering of aliens.
 

UVA10570-Meeting with Aliens(枚举) Sample Input

4
1 2 3 4
4
4 3 2 1
4
2 3 1 4
0
 

UVA10570-Meeting with Aliens(枚举) Sample Output

0
0
1

题解:这个题很有价值。想到倍长数列是比较自然的,但是接下来怎么办,如何快速求出将一个序列排成有序的最小交换次数,这里要用到一个结论:对于一个长度为n的元素互异的序列,通过交换实现有序的最小的交换次数是=n - n被分解成单循环的个数。具体证明见如下博客:

https://blog.csdn.net/wangxugangzy05/article/details/42454111

明白了这个,题目就变得很简单了,枚举起点,dfs找环,取最大值得出结果,这里要注意一点就是序列既可以是升序,也可以是降序,因此要倒着再枚举一遍,方法不变。

 #include <bits/stdc++.h>

 using namespace std;

 const int maxn =  + ;

 int n;
int num[maxn << ];
bool vis[maxn]; void dfs(int st, int a) {
if (vis[a]) return;
vis[a] = true;
dfs(st, num[st + a - ]);
} void dfs2(int st, int a) {
if (vis[a]) return;
vis[a] = true;
dfs2(st, num[st - a + ]);
} int main()
{
//freopen("input.txt", "r", stdin);
while (~scanf("%d", &n) && n) {
for (int i = ; i < n; i++) {
scanf("%d", &num[i]);
num[i + n] = num[i];
} int Max = ; for (int st = ; st < n; st++) {
memset(vis, false, sizeof(vis));
int cnt = ;
for (int i = st; i < st + n; i++) {
if (!vis[num[i]]) {
dfs(st, num[i]);
cnt++;
}
}
Max = Max > cnt ? Max : cnt;
} for (int st = * n - ; st >= n; st--) {
memset(vis, false, sizeof(vis));
int cnt = ;
for (int i = st; i >= st - n + ; i--) {
if (!vis[num[i]]) {
dfs2(st, num[i]);
cnt++;
}
}
Max = Max > cnt ? Max : cnt;
} printf("%d\n", n - Max);
}
return ;
}