【HDOJ】1016 Prime Ring Problem

时间:2022-09-24 21:33:01

经典DP,写的可能麻烦了一些。

#include <stdio.h>
#define false 0
#define true 1 int is_prime[];
int is_visit[];
int sequence[]; void DFS(int, int, int); int main() { int i, j, k;
int n; is_prime[] = false;
is_prime[] = true; for (i=; i<=; i++) {
k = ;
for (j=; j*j<=i; j++) {
if (i%j == ) {
k = ;
break;
}
}
if (k) {
is_prime[i] = false;
} else {
is_prime[i] = true;
} } k = ; while (scanf("%d", &n) != EOF) {
printf("Case %d:\n", ++k); DFS(, , n); printf("\n");
} return ;
} void DFS(int num, int order, int end) {
int i; is_visit[num] = true;
sequence[order] = num; if (order == end) {
if (is_prime[num+]) {
sequence[order] = num;
for (i=; i<=end; i++) {
if (i != end)
printf("%d ", sequence[i]);
else
printf("%d\n", sequence[i]);
}
}
} else {
for (i=; i<=end; i++) {
if (is_visit[i] == false && is_prime[i+num]) {
DFS(i, order+, end);
is_visit[i] = false;
}
}
}
}