HDOj-1016 Prime Ring Problem

Prime Ring Problem

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


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
 
#include<stdio.h>
#include<string.h>
int n;
int isp[45];
int cir[22];
int vis[22];
void is_prime()
{
    int i,j;
    for(i = 2;i <= 40;i ++)
    {
        for(j = 2;j <= i/2;j ++)
            if(i%j==0)
                isp[i] = 1;
    }
    return ;
}

void dfs(int cnt)
{
    int i,j;
    if(cnt == n && !isp[cir[0]+cir[n-1]])
    {
        for(j = 0;j < n-1;j ++)
            printf("%d ",cir[j]);
        printf("%d\n",cir[n-1]);
    }
    else
    {
        for(i = 2;i <= n;i ++)
        {
            if(!vis[i]&&!isp[i+cir[cnt-1]])
            {
                cir[cnt] = i;
                vis[i] = 1;
                dfs(cnt+1);
                vis[i] = 0;
            }
        }
    }
}

int main()
{
    int i,c = 0;
    is_prime();
    while(~scanf("%d",&n))
    {
        memset(vis,0,sizeof(vis));
        c++;
        printf("Case %d:\n",c);
        for(i = 0;i < n;i ++)
            cir[i] = i+1;
        dfs(1);
        printf("\n");
    }
    return 0;
}
 

 

posted on 2013-09-25 00:03  ~Love()  阅读(149)  评论(0编辑  收藏  举报

导航