第一次写博客,心情有点小忐忑。

言归正传,hdu 1016。

Prime Ring Problem

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


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
 
分析:第一次做dfs类题目。看了别人的解题报告好久(http://blog.sina.com.cn/s/blog_8699703b0100vr4p.html),终于看懂了,然后依样画葫芦写了一份出来。加了一点自己的解释。
 
#include <stdio.h>
#include <string.h>
int n, a[21], b[21];                    //a[]用于存放符合条件的数     b[]用于存放该数是否已经使用,使用则存1,反之存0
int isprime(int a)                      //素数判定
{
    int i;
    if(a == 1)
    {
        return 1;
    }
    for(i = 2; i < a-1; i ++)
    {
        if(a % i == 0)
        {
            return 0;
            break;
        }
    }
    return 1;
}

void dfs(int p)                                   //此题重点-深度搜索
{
    int i;
    if(p == n && isprime(1+a[p-1]))               //当p==n时已搜索完毕,进行输出,注意空格的位置
    {
        printf("%d", a[0]);
        for(i = 1; i < n; i ++)
        {
            printf(" %d", a[i]);
        }
        printf("\n");
    }
    for(i = 2; i <= n; i ++)                     //类似函数递归的一个搜索
    {
        if(b[i] == 0 && isprime(i+a[p-1]))       //始终利用与前一个数加和判定是否为素数
        {
            b[i] = 1;
            a[p] = i;
            dfs(p+1);                            //搜索下一个数
            b[i] = 0;                            
        }
    }
}
int main()
{
    int t = 0;
    while(scanf("%d", &n) != EOF)
    {
        t++;
        memset(b, 0, sizeof(a));
        a[0] = 1;                              //素环第一个数是1
        b[1] = 1;
        printf("Case %d:\n", t);
        if(n % 2 == 0)                         //只有偶数才可以
        {
            dfs(1);
        }
        printf("\n");
    }
    return 0;
}