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

Prime Ring Problem HDU - 1016

时间:2018-11-03 15:24:09      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:write   ase   repr   oid   res   blank   pac   print   return   

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\n",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:\n",k++);
        dfs(1);
        printf("\n");
    }
    
} 

 

Prime Ring Problem HDU - 1016

标签:write   ase   repr   oid   res   blank   pac   print   return   

原文地址:https://www.cnblogs.com/astonc/p/9900721.html

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