uva 331 Mapping the Swaps 求交换排序的map 纯DFS

时间:2023-03-09 09:30:31
uva 331 Mapping the Swaps 求交换排序的map 纯DFS

给出一个序列,每次交换两个数,求有几种交换方法能使序列变成升序。

n不大于5,用dfs做。

代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; int num[8], ans, n; bool check() { //check if the array is inorder
for (int i = 0; i < n - 1; i++)
if (num[i] > num[i + 1])
return false;
return true;
} void dfs(void) {
for (int i = 0; i < n - 1; i++)
if (num[i] > num[i + 1]) {
swap(num[i], num[i + 1]);
if (check())
ans++;
else
dfs();
swap(num[i], num[i + 1]);
}
} int main () {
int cas = 0;
while (scanf("%d", &n) && n) {
for (int i = 0; i < n; i++)
scanf("%d", &num[i]);
ans = 0;
if (!check()) dfs();
printf("There are %d swap maps for input data set %d.\n", ans, ++cas);
}
return 0;
}