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

hdu 1016 Prime Ring Problem(dfs)

时间:2014-12-09 17:17:50      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   ar   color   os   sp   

Prime Ring Problem

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 28391    Accepted Submission(s): 12644


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.

bubuko.com,布布扣
 

 

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
 
重新做了一遍素数环 没想到还是出了点小问题
 
从第一个数开始dfs 按字典序把符合条件的数计入seq数组
再通过回溯 把所有的情况都遍历并输出
(n==1的情况数据中不会出现 判不判断都可以)
 
bubuko.com,布布扣
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int vis[50];
int seq[50];
int prime[100];
bool okp(int x)
{
  int i;
  for(i=2;i<=sqrt(x);i++)
  {
    if(x%i==0) break;
  }
  if(i>sqrt(x)) return true;
  return false;
}
void prim()
{
  memset(prime,0,sizeof(prime));
  int i;
  for(i=2;i<=50;i++)
  {
    if(prime[i]==0)
    {
      if(okp(i))
        prime[i]=1;
    }
    int k=i,tc=2;
    while(k*tc<=50)
    {
      prime[k*tc]=2;
      tc++;
    }
  }
}
void dfs(int x)
{
  int i;
  if(x>n) return ;
  if(x==n&&prime[seq[x]+1]==1)
  {
    for(i=1;i<=n;i++)
    {
      printf("%d",seq[i]);
      printf("%c",i==n?\n: );
    }
  }
  else
  {
    for(i=2;i<=n;i++)
    {
      if(vis[i]==0&&prime[seq[x]+i]==1)
      {
        vis[i]=1;
        seq[x+1]=i;
        dfs(x+1);
        vis[i]=0;
      }
    }
  }
}
int main()
{
  int cas=1,i,j;
  prim();//筛法求素数
  while(scanf("%d",&n)!=EOF)
  {
    printf("Case %d:\n",cas++);
    //if(n==1) continue;  //测试数据中不会出现n==1
    memset(vis,0,sizeof(vis));
    seq[1]=1;
    vis[1]=1;    
    dfs(1);
    printf("\n");
  }
  return 0;
}
View Code

 

hdu 1016 Prime Ring Problem(dfs)

标签:des   style   blog   http   io   ar   color   os   sp   

原文地址:http://www.cnblogs.com/sola1994/p/4153395.html

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