标签:
第一次无指导写的回溯。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
int n, ans[25];
const int pn[] = {1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41};
bool isPrimeNumber(int x) {
for (int i = 0; i != 14; ++i) {
if (x == pn[i]) return true;
}
return false;
}
void dfs(int cur) {
if (cur + 1 == n) {
for (int i = 0; i != n - 1; ++i) {
printf("%d ", ans[i]);
}
printf("%d\n", ans[n - 1]);//结尾不能多空格
} else {
for (int i = 1; i != n + 1; ++i) {
bool ok = true;
for (int j = 0; j != cur + 1; ++j) {
if (i == ans[j]) {
ok = false;
break;
}
}
if (!ok) continue;
if ((cur != n - 2 || (cur == n - 2 && isPrimeNumber(i + 1)) )
&& isPrimeNumber(i + ans[cur])) {
ans[cur + 1] = i;
dfs(cur + 1);
}
}
}
}
int main() {
int kase(0);
while (scanf("%d", &n) == 1) {
if (kase) printf("\n");//最后一行不能多空行,否则WA
memset(ans, 0, sizeof(ans));
printf("Case %d:\n", ++kase);
ans[0] = 1;
dfs(0);
}
return 0;
}
UVa 524 Prime Ring Problem (回溯)
标签:
原文地址:http://www.cnblogs.com/liangyongrui/p/4678106.html