HDOJ-1016 素数环问题[DFS()]

Prime Ring Problem

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


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.

HDOJ-1016 素数环问题[DFS()]
 

 

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
 

 

Recommend
JGShining
 
 
最近一直在做一些比较基础的搜索题,培养感觉,很多题目在控制还是不太够,希望能够早日找到做搜索题的诀窍,不过想到还有一大堆搜索题在等着我去A,就很兴奋!
 
code:
 
 1 #include<iostream>

 2 #include<cmath>

 3 using namespace std;

 4 

 5 int vst[22];

 6 int n;

 7 int ans[22];

 8 int data[41];

 9 //2,3,5,7,11,13,17,19,23,29,31,37,41

10 

11 bool check(int x,int y)

12 {

13     if(!vst[y]&&data[x+y])

14         return 1;

15     else

16         return 0;

17 }

18 

19 void DFS(int depth)               //生成数组的长度

20 {

21     int i;

22     if(depth==n)

23     {

24         if(data[1+ans[n-1]])

25         {

26             printf("1");

27             for(i=1;i<n;i++)

28                 printf(" %d",ans[i]);

29             printf("\n");

30         }

31         return;

32     }

33     for(i=2;i<=n;i++)

34     {

35         if(check(ans[depth-1],i))

36         {

37             ans[depth]=i;

38             vst[i]=1;            //已访问

39             DFS(depth+1);

40             vst[i]=0;

41         }

42     }

43 }

44 

45 int main()

46 {

47     int cases=1;

48     data[2]=data[3]=1;

49     data[5]=data[7]=1;

50     data[11]=data[13]=1;

51     data[17]=data[19]=1;

52     data[23]=data[29]=1;

53     data[31]=data[37]=data[41]=1;

54     while(~scanf("%d",&n))

55     {

56         printf("Case %d:\n",cases++);

57         memset(vst,0,sizeof(vst));

58         ans[0]=1;

59         vst[1]=1;

60         DFS(1);

61         printf("\n");

62     }

63     return 0;

64 }


这题DFS()里传递一个数组层数的想法还是不错的,代码大体符合模板,所以难度不很高,希望通过多做题能够慢慢体会到搜索题的本质。那样不管做什么题都不怕啦!:)

你可能感兴趣的:(DFS)