HDU1016 Prime Ring Prublem
目錄
題目
題目出處:http://acm.hdu.edu.cn/showproblem.php?pid=1016
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個數組成一個環,n個數為1,2,…,n自然數, 兩兩相鄰相加和為素數,頭尾相加也為素數,列出n個數時所有的排列情況。
思路
- 由於n非常小,所以可以先使用素數篩去尋找範圍內的所有素數 。
- 再利用深搜對每種情況進行遍歷,如果發現某個數的情況無法湊出一個環,進行回溯。直到所以遍歷所有情況。
程式碼實現
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
int n;
int vis[41];
int ans_num[21];
int prime_num[41];
void prime() //素數篩 找出40以內的素數.
{
memset(prime_num,0,sizeof(prime_num));
int m=sqrt(40);
prime_num[1]=1;
for(int i=2;i<=m;++i)
{
if(!prime_num[i])
{
for(int j=i*i;j<=40;j+=i)
{
prime_num[j]=1;
}
}
}
}
void dfs(int x) //深搜
{
if(x==n&&prime_num[ans_num[0]+ans_num[n-1]]==0) //當到該情況遍歷到最後一個數時,比較頭尾相加是否是素數是則符合進行輸出
{
for(int i=0;i<n;++i)
{
if(i!=0) cout<<" ";
cout<<ans_num[i];
}
cout<<endl;
}
else //對每一個數進行適配搜尋
{
ans_num[0]=1;
vis[1]=1;
for(int i=2;i<=n;++i) //對每種數字情況進行遍歷
{
if(!vis[i]&&prime_num[i+ans_num[x-1]]==0) //如果該數沒被使用過以及與上一個數相加為素數則符合條件
{
ans_num[x]=i; //把符合條件的數加入陣列
vis[i]=1; //標記為已使用該數字
dfs(x+1); //對下一個數進行搜尋
vis[i]=0; //回溯的關鍵,若陣列x位置加x+1位置的數無論如何都不符合,則會回到這裡對x位置的數進行變更,重新整理數字的使用狀態。
}
}
}
}
int main()
{
int m=1;
memset(vis,0,sizeof(vis));
prime();
while(cin>>n)
{
if(n==-1) break;
cout<<"Case "<<m++<<":"<<endl;
dfs(1);
cout<<endl;
}
}