标签:sum lex idt order res blog 回归 log series
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.
Inputn (0 < n < 20).
OutputThe 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
递归求解
#include<iostream> #include<cstring> #include<cmath> using namespace std; int a[22],b[22],mark[22]; int prime(int x)//判断是否是素数 { int o=sqrt(x); if(x==1 || x==4) return 1; if(x==2 || x==3) return 0; for(int i=2;i<=o;i++) { if(x%i==0) return 1; } return 0; } void print(int n,int b[])//输出 { for(int i=1;i<=n;i++) { if(i!=1) cout<<‘ ‘; cout<<b[i]; } cout<<endl; } int judge(int front,int last,int k,int n)//递归判断素数环 { if(prime(front+last)) return 0; b[k]=last; if(k==n && !prime(last+1)) { print(n,b); return 1; } mark[last]=0;//标记是该数在子函数内不能在出现,但是回归主函数时必须释放 for(int i=2;i<=n;i++) { if(mark[i] && judge(last,i,k+1,n)) break; } mark[last]=1; return 0; } int main() { int count=1,n; while(cin>>n) { for(int i=1;i<=n;i++) { mark[i]=1; } b[1]=1; cout<<"Case "<<count++<<":"<<endl; if(n==1) cout<<n<<endl;//1单独输出 else { for(int i=2;i<=n;i++) { judge(1,i,2,n); } cout<<endl; } } return 0; }
#include <iostream> #include <algorithm> #include<cmath> using namespace std; int a[30],vis[30]; int prime(int x) { int o=sqrt(x); if(x==1 || x==4) return 1; if(x==2 || x==3) return 0; for(int i=2;i<=o;i++) { if(x%i==0) return 1; } return 0; } void dfs(int n,int m){ if(n>m && prime(a[1]+a[m])==0){ for(int i=1;i<=m;i++){ if(i!=1) cout<<‘ ‘; cout<<a[i]; } cout<<endl; } for(int i=2;i<=m;i++){ if(vis[i]==0){ a[n]=i; if(n==1 || (prime(i+a[n-1])==0)){ vis[i]=1; dfs(n+1,m); vis[i]=0; } } } } int main(){ int n,count=1; while(cin>>n){ cout<<"Case "<<count++<<":"<<endl; a[1]=1; vis[1]=1; dfs(2,n); cout<<endl; } return 0; }
标签:sum lex idt order res blog 回归 log series
原文地址:http://www.cnblogs.com/shinianhuanniyijuhaojiubujian/p/6579661.html