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
這里解釋下問題,輸入一個數n 把1-n中的數組成一個環,使環上相鄰的兩個數相加為素數,輸出所有可能的結果。
分析:
首先可以明確這是一個典型的DFS深度優先算法題。為了不出現重復的數字我們必須要有一個數組used[]標記數字是否使用,定義數組a[] 用于記錄下標為k時該處的數字,因為第一個數是1 所以從下標1開始不斷遞歸,定義一個臨時變量i,i從2開始不斷遞增,如果a[k-1]+i是素數,并且i沒有使用過就將數字used[i]標記為; a[k] = i 再搜索下一個下標k+1 處的數字。有一點,在一次遞歸后used為要標記為0;
#include <iostream>//HDU 1016 DFS 素數環
#include<string.h>
using namespace std;
int a[21]={1},n,used[21]; //a[0] 永遠為1
int f(int n) //判斷是否為素數
{
for(int i=2;i<=n-1;i++)
if(n%i==0)return 0;
return 1;
}
void dfs(int k)
{
if(k==n&&f(a[0]+a[n-1])) //如果遞歸到下標n并且滿足條件就找到一組正確的數據了
{
for(int i=0;i<n-1;i++)
cout<<a[i]<<" ";
cout<<a[n-1]<<endl;
}
else
{
for(int i=2;i<=n;i++)
if(used[i]==0&&f(a[k-1]+i)) //如果i沒有使用過,并且a[k-1]和i相加為素數
{
a[k]=i; //記錄下標的值
used[i]=1; //標記為使用過的
dfs(k+1); //開始下一個下標的計算
used[i]=0;//清除標記
}
}
}
int main(int argc, char *argv[])
{
int c=1;
while(cin>>n)
{
memset(used,0,sizeof(used));
cout<<"Case "<<c++<<":"<<endl;
used[0]=1; //第一個數永遠是1,所以下標0要標記為使用過的
dfs(1); //開始從下標1開始找
cout<<endl;
}
return 0;
}