HDU 1016--DFS第一炮

本文介绍如何使用深度搜索算法解决素数环问题,即在一定范围内将自然数排列成圆环,使得相邻两数之和为素数。通过构建素性数组并递归搜索符合条件的序列,实现算法求解。

                                                                                     HDU 1016 

                                                                                                               --DFS第一炮

题目:

                

                                                              Prime Ring Problem

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

 

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

 

Source
Asia 1996, Shanghai (Mainland China)

 

Recommend
JGShining

分析:

      该题讲述了要求一个素数环,使得相邻的两个数之和为素数,求其各种素数环。由于它为层层递进,故想到深度搜索DFS,又由于0<n<20,则简单地设置了一个素性数组。

代码:

 1 #include<stdio.h>
2 #include<string.h>
3
4 int prime[39]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0};//判定1-38素性数组
5 int ans[20],visit[20],num;
6
7 void dfs(int n)
8 {
9 int i;
10 if(n==num&&prime[ans[0]+ans[n-1]]==1)
11 {
12 for(i=0;i<n-1;i++)
13 printf("%d ",ans[i]);
14 printf("%d\n",ans[n-1]);
15 }
16 else
17 {
18 for(i=2;i<=num;i++)
19 {
20 if(!visit[i]&&prime[ans[n-1]+i]==1)
21 {
22 visit[i]=1;
23 ans[n]=i;
24 dfs(n+1);
25 visit[i]=0;
26 }
27 }
28 }
29 }
30
31 int main()
32 {
33 int i=1;
34 ans[0]=1;
35 while(scanf("%d",&num)!=EOF)
36 {
37 memset(visit,0,sizeof(visit));
38 printf("Case %d:\n",i++);
39 dfs(1);
40 printf("\n");
41 }
42 return 0;
43 }

PS.最近感冒严重了,好难受。。。

 

转载于:https://www.cnblogs.com/hankers/archive/2012/01/25/2329339.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值