暑假集训第四周周六赛 A - Prime Ring Problem素数环


A - Prime Ring Problem
Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit  Status  Practice  HDU 1016

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
分析:

这是一道典型的深搜,对于这种题目我还是不够熟悉,不知道如何去做,每次比赛都感觉自己学的太少太少

另外就是打表是一个非常好的提高运行效率的办法

这个题看完别人的代码感觉好简单,我知道,我必须去好好做这种题,在自己的脑子里有这种思路,这种思想

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<stdio.h>
#include<string.h>
int v[21],a[21],n,p[38]= {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,01,0,1,0,0,0,0,0,1};

void DFS(int cur)
{
    if(cur==n&&p [a[0]+a[n-1]])
    {
        printf("%d",a[0]);
        for(int  i=1; i<n; i++)
            printf(" %d",a[i]);
        printf("\n");
    }
    else
        for(int i=2; i<=n; i++)
            if(!v[i]&&p[i+a[cur-1]])
            {
                a[cur]=i;
                v[i]=1;
                DFS(cur+1);
                v[i]=0;
            }
}
int main()
{
    int cut=1;
    a[0]=1;
    while(~scanf("%d",&n))
    {
        memset(v,0,sizeof(v));
        printf("Case %d:\n",cut++);
        DFS(1);
        printf("\n");
    }
    return 0;
}


你可能感兴趣的:(动态规划)