hdu1016Prime Ring Problem

来源:互联网 发布:苹果助手下载软件 编辑:程序博客网 时间:2024/05/17 04:57

【大意】

给定数n(n<20),在n的所有排列中,记a[1],a]2],...,a[n],求满足a[i]+a[i+1](1<=i<n)是素数并且a[1]+a[n]也是素数的所有排列。排列按字典序输出。

【分析】

经典的搜索问题。

先搜索19+18以内的素数,记vis[i]:true表示i是合数,false表示是质数

记can[i][j]:true表示i+j是素数,false表示是合数

顺序从小到大搜索即可,注意相邻2个数必然奇偶不同,这样搜索到的结果满足字典序。

由于是素数环要求,可以双向搜索,但结果不一定是字典序,可用set保存。

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

68
 

Sample Output

Case 1:1 4 3 2 5 61 6 5 2 3 4Case 2:1 2 3 8 5 6 7 41 2 5 8 3 4 7 61 4 7 6 5 8 3 21 6 7 4 3 8 5 2
 
#include<cstdio>#include<algorithm>#include<iostream>#include<cstring>#include<cmath>using namespace std;int n;int num[100]={0};int vis[100]={0};int prim(int x){    for(int i=2; i<=sqrt(x); i++)    {        if(x%i==0)            return 0;    }    return 1;}void dfs(int k){    if(k>n&&prim(num[n]+num[1]))    {        for(int i=1; i<n; i++)            printf("%d ",num[i]);        printf("%d\n",num[n]);    }    else    {        for(int i=2; i<=n; i++)        {            if(!vis[i]&&prim(i+num[k-1]))            {                vis[i]=1;                num[k]=i;                dfs(k+1);                vis[i]=0;            }        }    }}int main(){  int Case=1;    while(~scanf("%d",&n))    {        printf("Case %d:\n",Case);        num[1]=1;        dfs(2);        printf("\n");       Case++;    }    return 0;}


0 0
原创粉丝点击