Prime Ring Problem HDU - 1016

Posted astonc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Prime Ring Problem HDU - 1016相关的知识,希望对你有一定的参考价值。

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. 

技术分享图片 

Inputn (0 < n < 20). 
OutputThe 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遍历所有结果
AC Code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int N;
int a[21];
int vis[21];
int p[17]={2,3,5,7,11,13,17,19,23,29,31,37,39,41,43,47};
bool prime(int x){
    for(int i=0;i<17;i++)
        if(p[i]==x)
            return true;
    return false;
}
void dfs(int k){
    if(k==N&&prime(a[1]+a[N])){
        for(int i=1;i<N;i++)
            printf("%d ",a[i]);
        printf("%d
",a[N]);
    }
    else{
        for(int i=2;i<=N;i++){
            if(!vis[i]&&prime(i+a[k])){
                vis[i]=1;
                a[k+1]=i;
                dfs(k+1);
                vis[i]=0;//取消标记
            }
        }
    }
}
int main(){
    int k=1;
    while(~scanf("%d",&N)){
        
        memset(vis,0,sizeof(vis));
        a[1]=1;vis[1]=1;
        printf("Case %d:
",k++);
        dfs(1);
        printf("
");
    }
    
} 

 














以上是关于Prime Ring Problem HDU - 1016的主要内容,如果未能解决你的问题,请参考以下文章

hdu1016 Prime Ring Problem

HDU 1016 Prime Ring Problem

HDU-1016-Prime Ring Problem

Prime Ring Problem HDU - 1016

HDU 1016 Prime Ring Problem

HDU 1010 Prime Ring Problem