码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1016 Prime Ring Problem (简单DFS)

时间:2014-07-19 22:23:15      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

Prime Ring Problem

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


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.

bubuko.com,布布扣
 

 

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

 

 
       题意:n个人围在一起,任意2个相邻的之和为素数,输出所有的可能的情况,但情况还是要按一定的规则输出,就是前面的数字由小到大的输出情况。每个case后右一个空格,注意一下格式吧。
 
        解题思路:从第一个位置开始,判断下一个位置加入哪一个数,并判断是否合适。若合适则标记加入,不断for循环,做好DFS的判断条件。
 
 
贴出代码:
 
#include <stdio.h>
#include <string.h>

int visited[25], foot[25];
int x[11]= {3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};

int Prime(int a, int b)
{
    int  mark = 0;

    for(int i = 0; i<11; i++)
    {
        if( a+b == x[i] )
        {
            mark = 1;
            break;
        }
    }

    return mark;
}

void DFS(int n, int m)
{
    if(m == n)
    {
        if(Prime(foot[1], foot[n]))
        {
            for(int i = 1; i<n; i++)
            {
                printf("%d ", foot[i]);
            }
            printf("%d\n", foot[n]);
            //printf("\n");
        }
    }
    else
    {
        for(int i = 1; i<=n; i++)
        {
            if(visited[i])
                continue;
            if(Prime(foot[m], i) == 1)
            {
                foot[m+1] = i;
                visited[i] = 1;
                DFS(n, m+1);
                visited[i] = 0;
            }
        }
    }
}

int main()
{
    int n, k = 1;
    while(scanf("%d", &n)!=EOF)
    {
        if(n<=0 || n>=20)
            break;
        memset(visited, 0, sizeof(visited));
        visited[1] = 1;
        foot[1] = 1;
        printf("Case %d:\n", k++);
            DFS(n, 1);
        printf("\n");
    }

    return 0;
}

 

hdu 1016 Prime Ring Problem (简单DFS),布布扣,bubuko.com

hdu 1016 Prime Ring Problem (简单DFS)

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/fengxmx/p/3855108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!