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题意:一个环任意相邻的两个数加起来都是素数。输入一个n ,然后给1--n 的数字排序 ,使之满足素数环的条件。思路:一道深度搜索, 要注意的是开头的永远是1 。Code: #if 0 #include<iostream> #include<cmath> using namespace std; int N , toal; bool pd[21] ; int ret[21] ; int prime(int a ,int b) { int x=a+b ,cnt=2; int sqrx=sqrt(x) ; while(cnt<=sqrx&&x%cnt!=0) cnt++; if(cnt>sqrx) return 1; else return 0 ; } int show() { for(int i=1 ; i < N ;i++) cout << ret[i]<<" " ; cout << ret[N]<< endl; } int dfs(int t,int n) //t代表第几层 { int i ; for(i = 1 ; i <= n ; i++) { if(prime(ret[t-1],i) && !pd[i]) { ret[t]=i; pd[i]=1; if(t==n) { if(prime(ret[n],ret[1])&&ret[1]==1) show(); } else dfs(t+1,n) ; pd[i]=0; } } } int main() { while(cin>>N) { toal++ ; cout << "Case "<<toal<<":"<<endl; dfs(1,N) ; cout << endl; } } #endif
本文介绍了一种基于深度优先搜索的算法,用于解决素数环问题。该问题要求将1到n的数字放置在一个环形结构中,使得任意相邻两数之和为素数,并且首位数字固定为1。文章提供了完整的C++实现代码。
513

被折叠的 条评论
为什么被折叠?



