Prime Ring Problem
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
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
Asia 1996, Shanghai (Mainland China)
題外話:
省賽的失利也不能阻擋我前進的腳步,經歷過就是一件好事,正如老師所說的,結果誰也沒法預測,但這個過程是實實在在的,自己可以在其中收獲很多東西。人生中需要經歷很多事情,有些事情,只有親身經歷過才會懂。
解題思路:
素數環要求任何相鄰的兩個數相加的和必須為素數。用DFs,從一年前期末考試兩個多小時也沒做出來這個題到現在的一次Ac,自己真的進步了。
代碼:
#include
#include
#include
#include
using namespace std;
const int maxn=25;
bool visit[maxn];
int num[maxn];
int n;
bool prime(int n)
{
if(n==1)
return false;
if(n==2)
return true;
if(n%2==0)
return false;
for(int i=3;i<=(int)sqrt(n);i+=2)
if(n%i==0)
return false;
return true;
}
void dfs(int step)
{
if(step>n&&prime(num[n]+num[1]))
{
for(int i=1;i<=n-1;i++)
cout<>n)
{
cout<<"Case "<