HDU-1016,Prime Ring Problem(DFS+素数)

简介: HDU-1016,Prime Ring Problem(DFS+素数)

Problem 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开头的排列 。


程序代码:


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define N 100001
int num[N],vis[N],n;
int prime(int x)//素数判定 
{
  if(x<2)
    return 0;
  for(int i=2;i<=sqrt(x);i++)
    if(x%i==0)
      return 0;
  return 1;
}
void dfs(int a)
{
  if(a==n&&prime(num[a-1]+1))//这个数达到n,并且满足最后一个数和第一个数的和仍是素数 
  {
    printf("1");
    for(int i=1;i<n;i++)
      printf(" %d",num[i]);//依次输出,保证最后一个数的后面没有空格 
    printf("\n");
  }
  if(a==n)//返回 
    return ;
  for(int i=2;i<=n;i++)
  {
    if(prime(num[a-1]+i)&&!vis[i])//从2开始向后搜索,且这个数没有标记过 
    {
      num[a]=i;//赋值给对应的数 
      vis[i]=1;//标记这个数 
      dfs(a+1);//搜索下一个 
      vis[i]=0;//取消标记 
    }
  }
}
int main()
{
  int ans=0;
  while(~scanf("%d",&n))
  {
    memset(vis,0,sizeof(vis));
    num[0]=1;//第一个数为1 
    vis[1]=1;//将1标记,已经出现过 
    printf("Case %d:\n",++ans);
    dfs(1);
    printf("\n");
  }
  return 0;
}


相关文章
|
8月前
|
算法
1091 zoj Knight Moves的BFS算法和DFS
1091 zoj Knight Moves的BFS算法和DFS
35 0
|
5月前
|
Java
hdu1016 Prime Ring Problem【素数环问题(经典dfs)】
hdu1016 Prime Ring Problem【素数环问题(经典dfs)】
24 0
|
8月前
uva10783 Odd Sum
uva10783 Odd Sum
34 0
HDOJ 1016 Prime Ring Problem素数环【深搜】
HDOJ 1016 Prime Ring Problem素数环【深搜】
89 0
HDOJ 1016 Prime Ring Problem素数环【深搜】
|
C语言
HDOJ 1016 Prime Ring Problem素数环【深搜2】
HDOJ 1016 Prime Ring Problem素数环【深搜】
78 0
ZOJ Problem Set - 3758 素数
ZOJ Problem Set - 3758 素数
80 0