您的位置:首页 > 其它

HDU 1016 Prime Ring Problem (DFS)

2016-05-28 11:53 453 查看

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 41149    Accepted Submission(s): 18218


[align=left]Problem Description[/align]
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.



 

[align=left]Input[/align]
n (0 < n < 20).

[align=left]Output[/align]
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.

[align=left]Sample Input[/align]

6
8

[align=left]Sample Output[/align]

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

[align=left]Source[/align]
Asia 1996, Shanghai (Mainland China)
 
题解:输入n ,从1开始,把n(1~n)的数围成一个环,要使每两个相邻的数加起来都是素数。
          dfs撸一波。。。

AC代码:
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<cstdlib>
#include<iomanip>
#include<vector>
#include<list>
#include<map>
#include<queue>
#include<algorithm>
using namespace std;
int a[30],b[30];
int n,cas=0;
int prime(int x)
{
int i;
for(i=2;i*i<=x;i++)
if(x%i==0)return 0;
return 1;
}
void dfs(int x,int y)
{
for(int i=1;i<=n;i++)
{
if(b[i]==0)
{
if(prime(x+i)==1)
{
b[i]=1; //标志i用过
a[y]=i;  //储存 i 的值
dfs(i,y+1); //继续搜
b[i]=0;   //没有搜到就标志当前的 i 没用过
}
}
}
if(y==n+1) //n+1个是结束标志
{
if(prime(x+1)==1) //判断最后一个和第一个,即 1 相加是否成立
{
for(int i=1;i<n;i++)
printf("%d ",a[i]);
printf("%d\n",a
);
}
}
}
int main()
{

while(cin>>n)
{
printf("Case %d:\n",++cas);
a[1]=1;
b[1]=1;
dfs(1,2);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: