#include <stdio.h>
int n, store[21], Prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43 };
bool hasSelect[21], ok;
bool checkPrime(int k){
for(int i = 0; i < 14; ++i)
if(k == Prime[i]) return 1;
return 0;
}
void backTrack(int k){
if(k == n + 1){
if(checkPrime(store[1] + store[n])){
printf("%d", store[1]);
for(int i = 2; i <= n; ++i) printf(" %d", store[i]);
printf("\n");
ok = 1;
}
return;
}
for(int i = 2; i <= n; ++i){
if(!hasSelect[i] && checkPrime(i + store[k - 1])){
hasSelect[i] = 1;
store[k] = i;
backTrack(k + 1);
hasSelect[i] = 0;
}
}
}
int main(){
int i = 1;
while(scanf("%d", &n), n){
printf("Case %d:\n", i++);
if(n & 1){
if(n == 1) printf("1\n");
else printf("No Answer\n");
continue;
}
ok = 0;
store[1] = 1;
backTrack(2);
if(!ok) printf("No Answer\n");
}
return 0;
}| 815818 | 长木 | 素数环 | Accepted |
28 | 232 | C/C++ | 04-15 10:46:05 |
NYOJ488 素数环 【回溯】+【预处理】,布布扣,bubuko.com
原文:http://blog.csdn.net/chang_mu/article/details/23743479