1016 Prime Ring Problem 搜索(深搜)

来源:互联网 发布:java socket编程 编辑:程序博客网 时间:2024/05/17 00:50

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 17830    Accepted Submission(s): 8018


Problem Description
A 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
68
 
#include<iostream>#include<cstring>#include<cmath>using namespace std;int num;  //记录个数int vis[21];  //记录是否被访问int a[21];  //记录所走路径bool ok;bool isprime(int n){int i=2;for(i;i<=(int)sqrt(n*1.0)+1;i++){if(n%i==0){return false;}}return true;}void show(){cout<<a[1];for(int i=2;i<=num;i++){cout<<" "<<a[i];}cout<<endl;}void dfs(int n,int d)   //当前节点是第n个节点,为数字d{if(n==num){if(isprime(d+a[n-1])&&isprime(d+a[1]))   //最后节点满足要求{a[n]=d;show();return;}}a[n]=d;for(int i=2;i<=num;i++){if(vis[i]==0){if(isprime(i+d)){vis[i]=1;dfs(n+1,i);}vis[i]=0;}}}int main(){int cs=0;while(cin>>num){cout<<"Case "<<++cs<<":"<<endl;memset(vis,0,sizeof(vis));memset(a,0,sizeof(a));a[1]=1;vis[1]=1;dfs(1,1);cout<<endl;}return 0;}


Sample Output
Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
原创粉丝点击