HDU - 1016 Prime Ring Problem
ring is compose of n circles as shown in diagram. Put natural number 1, 2, …, n into each circle separately, and the sum of numbers in two adjacent circles should be a prime.
Note: the number of first circle should always be 1.
Input
n (0 < n < 20).
Output
The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
Sample Input
6
8
Sample Output
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2
给出一个n,和一个环。在坏上放置n个数,即1-n,要求所有相邻的两个数之和都必须是质数,求满足该要求的所有序列,注意序列都是以1开始的。
DFS下去,觉得有点类似n皇后问题吧。
注意递归回溯之后把vis重置,因为回溯之后该点是可以走的。
AC代码:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cctype>
#include <cstdlib>
using namespace std;
int n , a[20],put[20];
bool isPrime(int num){
for(int k =2 ; k < num ; ++k){
if(num % k == 0) return false;
}
return true;
}
void dfs(int i){//放置第i个数
for(int j = 2 ; j <= n ; ++j){
if(i == n+1){
if(isPrime(1+put[n])){
for(int j = 1 ; j < n ; ++j){
printf("%d ",put[j]);
}
printf("%d\n",put[n]);
return;
}
}
if(a[j]) continue;
if(isPrime(j+put[i-1])){
put[i] = j;
a[j] = 1;
dfs(i+1);
a[j] = 0;
}
}
}
int main(){
int c = 1;
put[1]= 1;
while(~scanf("%d",&n)){
memset(a,0,sizeof(a));
printf("Case %d:\n",c++);
dfs(2);
printf("\n");
}
return 0;
}