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

HDU 1016 Prime Ring Problem

时间:2015-08-02 18:13:37      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

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
 
     题意:给一个数n,用1到n中的所有数围成一个环,并且每相邻的两个数相加为素数,问这样的环有多少个,并输出每个环。每个从1开始输出。
    这题用dfs搜索,每次从1开始搜。一要如何搜,那就看代码吧。
 
 
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,v[25],a[25];
int ssb[100],zj[100],pn;
void f()
{
    int i,j;
    zj[0]=1;
    zj[1]=1;
    pn=0;
    for (i=2;i<=100;i++)
    {
        if (zj[i]==0) ssb[pn++]=i;
        for (j=0;j<pn;j++)
        {
            if (i*ssb[j]>100) break;
            zj[i*ssb[j]]=1;
            if (i%ssb[j]==0) break;
        }
    }
}
void dfs(int x,int k)
{
    int i,j;
    for (i=2;i<=n;i++)
    {
        if (!v[i]&&zj[i+x]==0)
        {
            v[i]=1;
            a[k+1]=i;
            if (k+1==n)
            {
                if (zj[1+a[n]]==0){
                for (j=1;j<n;j++) printf("%d ",a[j]);
                printf("%d\n",a[n]);}
            }
            dfs(i,k+1);
            v[i]=0;
        }
    }
}
int main()
{
    int cut=1;
    a[1]=1;
    memset(zj,0,sizeof(zj));
    f();
    while (~scanf("%d",&n))
    {
        printf("Case %d:\n",cut);
        cut++;
        memset(v,0,sizeof(v));
        dfs(1,1);
        printf("\n");
    }
    return 0;
}

 

HDU 1016 Prime Ring Problem

标签:

原文地址:http://www.cnblogs.com/pblr/p/4696365.html

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