您的位置:首页 > 其它

【DFS】HDU1016Prime Ring Problem

2016-04-13 17:58 337 查看
题目链接: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

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int a[50];
int vis[50];
int n;
bool check(int a)
{
for(int i=2;i<a;i++){
if(a%i==0) return false;
}
return true;
}
void dfs(int cnt)
{
if(cnt==n&&check(a[0]+a[n-1])){ // 符合情况则输出结果;
for(int i=0;i<n-1;i++)
cout<<a[i]<<' ';
cout<<a[n-1]<<endl;
}
for(int i=2;i<=n;i++){
if(vis[i]==0){
if(check(i+a[cnt-1])){ // 判断下个数是否和上个数和为素数;
vis[i]=1;
a[cnt++]=i;
dfs(cnt);
vis[i]=0;
cnt--;
}
}
}
}
int main()
{
int Case=1;
while(cin>>n){
cout<<"Case "<<Case++<<":"<<endl;
memset(vis,0,sizeof(vis));
a[0]=1; // 起始位置为1;
dfs(1);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: