Prime Ring Problem
Time Limit:3000MS Memory Limit:0KB 64bit IO Format:%lld & %llu
Description
Prime Ring Problem
Prime Ring Problem |
A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 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 <= 16)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.
You are to write a program that completes above process.
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
Miguel A. Revilla
1999-01-11
题目大意:
输出换的排列方式,要求相邻的两数之和为质数。
解题思路:
DFS.
#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
int n,visited[25];
vector <int> path,v[25];
bool isPrime(int x){
for(int i=2;i*i<=x;i++){//不用sqrt,易损精度.
if(x%i==0)
return false;
}
return true;
}
void dfs(int s){
visited[s]=true;
path.push_back(s);
if(path.size()<n){
for(int i=0;i<v[s].size();i++){
int d=v[s][i];
if(visited[d]==false)
dfs(d);
}
}
else{
if(isPrime(path.back()+1)){
for(int i=0;i<n;i++){
if(i>0) printf(" ");
printf("%d",path[i]);
}
printf("\n");
}
}
path.pop_back();
visited[s]=false;
}
void solve(){
for(int i=1;i<=n;i++){
visited[i]=false;//初始化.
v[i].clear();
}
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(isPrime(i+j)){
v[i].push_back(j);
v[j].push_back(i);
}
}
}
dfs(1);
}
int main(){
int casen=0;
while(scanf("%d",&n)!=EOF){
if(casen>0) printf("\n");
printf("Case %d:\n",++casen);
solve();
}
return 0;
}