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 题目分析 : 1. 1的位置不变,从1开始DFS深搜; 2. 素数函数的效率决定了代码是否超时; 错误点 : 1. 素数的判断有误; 2. while(true) 的形式有误,无法跳出,时间超时;
#include <iostream> #include <math.h> #include <vector> #include <cstring> using namespace std; int n,m,array[25],mark[25],step,k=0; bool Exame_prime(int x,int y) { int sum = x+y; for(int i=2;i*i<=sum;i++) if(sum%i==0) return true; return false; } void DFS(int x) { step++; array[step] = x; if(step==n) { if(!Exame_prime(array[step],1)) { for(int i=1;i<=step;i++) { if(i!=step) cout << array[i] << " "; else cout << array[i]; } cout << endl; } return; } for(int i=2;i<=n;i++) { //cout <<"|||| :" << x <<" " <<i << " " <<mark[i] <<" " << ++k << "\n"; if(!Exame_prime(x,i) && !mark[i]) { mark[i]=1; DFS(i); mark[i]=0; step--;//不可省略,step为常数,不会回溯; } } } int main() { int m=0; while(cin >> n) { memset(mark,0,sizeof(mark)); step=0; cout << "Case " << ++m <<":" << "\n"; DFS(1); cout << endl; } return 0; }
时间: 2024-10-12 00:10:31