欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HDU 1016 Prime Ring Problem

程序员文章站 2022-05-21 08:48:51
...

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.

HDU 1016 Prime Ring Problem

 

 

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

#include <iostream>
#include<cstdio>
#include<string.h>
#define ll long long
using namespace std;
char a[10005];
int prime[100];
int vist[100];
int b[100];
int n;
void init()
{
    memset(prime,0,sizeof(prime));
    prime[1]=1;
    for(int i=2;i<=10;i++)
    {
        if(!prime[i])
        {
            for(int j=i*i;j<=100;j+=i)
            {
                prime[j]=1;
            }
        }
    }
   /* for(int i=0;i<20;i++)
    {
        if(!prime[i])
            cout<<i<<" ";
    }*/
    memset(vist,0,sizeof(vist));
}
void dfs(int num)
{
    //printf(" %d",x);
    if(num==n&&!prime[b[num-1]+b[0]])
    {
        for(int i=0;i<=num-1;i++)
        {
            if(!i) printf("%d",b[i]);
            else printf(" %d",b[i]);
        }
        printf("\n");
    }
    else
    {
        for(int i=2;i<=n;i++)
        {
            if(!vist[i])
            {
                if(!prime[i+b[num-1]])
                {
                    vist[i]=1;
                    b[num++]=i;
                    dfs(num);
                    vist[i]=0;
                    num--;
                }
            }
        }
    }
}
int main()
{
    int num=0;
    while(~scanf("%d",&n))
    {
        num++;
        init();
        b[0]=1;
        printf("Case %d:\n",num);
        dfs(1);
        printf("\n");
    }
    return 0;
}