您的位置:首页 > 其它

hdu 1016 Prime Ring Problem (DFS)

2013-11-28 09:01 423 查看

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21703 Accepted Submission(s): 9682


[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)

[align=left]Recommend[/align]
JGShining | We have carefully selected several similar problems for you: 1072 1175 1026 1258 1180

//250MS    232K    1064 B    G++
/*

题意:
给出一个数n,求数1到n组成的环,环相邻的两个数和为素数。输出符合条件的环。

DFS:
这道题我开始看了几次都没动手,怕功力不够写不出来。后来最多了再回来做,
发现也算是一道基础题而已。
因为n比较小,我这里先预处理符合条件的一对数的情况,保存在g中。然后直接深搜,
再用pre数组保存没个数的前驱,最后将符合条件的pirnt出来。

*/
#include<stdio.h>
#include<string.h>
int g[25][25]; //预处理
int vis[25];
int pre[25]; //前一个数
int n;
int judge(int x)
{
for(int i=2;i*i<=x;i++)
if(x%i==0) return 0;
return 1;
}
void init()
{
memset(g,0,sizeof(g));
for(int i=1;i<25;i++)
for(int j=i+1;j<25;j++)
if(judge(i+j)) g[i][j]=g[j][i]=1;
}
void print(int x)
{
int ans[25],i=1;
ans[0]=x;
while(pre[x]!=-1){
ans[i++]=pre[x];
x=pre[x];
}
for(int i=n-1;i>0;i--) printf("%d ",ans[i]);
printf("%d\n",ans[0]);
}
void dfs(int x,int cnt)
{
if(cnt==n && g[x][1]) print(x); //第一个和最后一个的和也是素数
for(int i=2;i<=n;i++){
if(!vis[i] && g[x][i]){
pre[i]=x;
vis[i]=1;
dfs(i,cnt+1);
vis[i]=0;
}
}
}
int main(void)
{
int k=1;
init();
while(scanf("%d",&n)!=EOF)
{
printf("Case %d:\n",k++);
memset(vis,0,sizeof(vis));
pre[1]=-1;
vis[1]=1;
dfs(1,1);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: