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.最近感冒严重了,好难受。。。