题意:有一个长度为n的序列,数字是从1到n,然后问至少交换多少次可以让序列成为升序或降序的序列,环是升序或降序也可以。比如 2 1 4 3也是可以的。
题解:把从1到n和从n到1所有成立情况放到数组内,共有2×n种情况,然后拿输入的序列和这2n种情况比对,不成功的交换后继续比对,直到完全匹配,找出交换次数最小值。
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N = 505;
int n, s[N + N][N], in[N];
int main() {
while (scanf("%d", &n) == 1 && n) {
for (int i = 0; i < n; i++) {
scanf("%d", &in[i]);
s[0][i] = i + 1;
}
for (int i = 1; i < n; i++) {
int temp = s[i - 1][0];
for (int j = 0; j < n - 1; j++)
s[i][j] = s[i - 1][j + 1];
s[i][n - 1] = temp;
}
int nn = n * 2;
for (int i = n; i < nn; i++)
for (int j = 0, k = n - 1; j < n; j++, k--)
s[i][j] = s[0][k];
for (int i = n + 1; i < nn; i++) {
int temp = s[i - 1][0];
for (int j = 0; j < n - 1; j++)
s[i][j] = s[i - 1][j + 1];
s[i][n - 1] = temp;
}
int res = 0x3f3f3f3f, temp[N];
for (int i = 0; i < nn; i++) {
int num = 0;
for (int j = 0; j < n; j++)
temp[j] = in[j];
for (int j = 0; j < n; j++) {
if (temp[j] != s[i][j]) {
num++;
for (int k = j + 1; k < n; k++)
if (temp[k] == s[i][j]) {
swap(temp[k], temp[j]);
break;
}
}
}
res = min(res, num);
}
printf("%d\n", res);
}
return 0;
}
时间: 2024-10-09 08:51:10