Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 51945 Accepted Submission(s): 23004
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.
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.
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
Source
这题用的dfs,题意:1到n组成个环,每两个相邻的数之和都要是素数才输出;
所以要用dfs把1传入得到1到n的全排列,边加边判断是不是素数,还有别忘了最后一个要加1判断
#include<iostream> #include<math.h> #include<string.h> using namespace std; //判断是否是素数 是为真,否为假 bool isprime(int x) { int y=floor(sqrt(x)+0.5); int i; if(x==0||x==1) return false; if(x==2) return true; for(i=2;i<=y;i++) { if(x%i==0) return false; } return true; } int n; bool visit[30];//访问数组 int a[30];//储存1到n的全排列 void dfs(int x) { if(x==n&&isprime(a[n-1]+1)) { int i; for(i=0;i<n;i++) { if(!i) cout<<a[i]; else cout<<" "<<a[i]; } cout<<endl; } else { int i; for(i=1;i<=n;i++) { if(!visit[i]&&isprime(i+a[x-1])) { a[x]=i; visit[i]=true; dfs(x+1); visit[i]=false; } } } } int main() { int k=1; while(cin>>n) { cout<<"Case "<<k++<<":"<<endl; int i; //初始化visit memset(visit,false,sizeof(visit)); visit[0]=true; a[0]=1; visit[1]=true; dfs(1); cout<<endl; } return 0; }
人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想。