735
技術社區[雲棲]
HDU1016 DFS
Prime Ring Problem
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 14601 Accepted Submission(s): 6667
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.

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.
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
Recommend
JGShining
題解:典型DFS 做法已經標記在 程序上了
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,ans[22];
bool isp[45];
bool vis[45];
void dfs(int p,int x) //p為當前第幾個可行數 x為可行的數
{
ans[p]=x;
vis[x]=1;
if(p==n) //當P等於n證明最後一個數與倒數第二個數相加為素數 隻需判斷是否跟1相加為素數
{
if(isp[ans[p]+1]) //判斷最後一個數是否與1相加為素數 如果是那麼該環成立 輸出結果
{
for(int i=1; i<=n; i++)
{
printf("%d",ans[i]);
if(i<n)
printf(" ");
else
printf("\n");
}
return ;
}
}
for(int i=1; i<=n; i++)
{
if(!vis[i]&&isp[ans[p]+i])
{
dfs(p+1,i);//符合值進入下一層搜索
vis[i]=0; //不符合 回溯上一層
}
}
return ;
}
int main()
{
int s=1;
memset(isp,1,sizeof(isp));
isp[1]=0;
isp[0]=0;
for(int i=2; i<=int(sqrt(40)); i++)//打出素數表
{
if(isp[i])
{
for(int j=2*i; j<=40; j+=i)
isp[j]=0;
}
}
while(scanf("%d",&n)!=EOF)
{
memset(vis,0,sizeof(vis));
cout<<"Case "<<s<<':'<<endl;
dfs(1,1);
s++;
cout<<endl;
}
return 0;
}
最後更新:2017-04-02 15:28:28