zoukankan      html  css  js  c++  java
  • HDOJ1016 Prime Ring Problem

    Prime Ring Problem

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


    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
     
     1 // 1:当n为奇数的时候, 肯定没有符合条件的:2:符合条件的排列相邻的数字的奇偶性肯定不同;
     2 
     3 #include<stdio.h>
     4 #include<string.h>
     5 
     6 int used[20],prime[40],path[20];
     7 void DFS(int num,int n)
     8 {
     9     int i;
    10     if(num>n&&prime[path[n]+path[1]])//判断第一个和最后一个数是否匹配
    11     {
    12         for(i=0;i<n;++i)
    13             printf(i?" %d":"%d",path[i+1]);
    14         printf("\n");
    15         return;
    16     }
    17     for(i=2;i<=n;++i)//生成开头数字为1的所有排列
    18     {
    19         if(!used[i]&&prime[path[num-1]+i])//如果相邻两个数的和为素数,继续 
    20         {
    21             used[i]=1;//将i标记为已用;
    22             path[num]=i;
    23             DFS(num+1,n);
    24             used[i]=0;//恢复原始状态
    25         }
    26     }
    27 }
    28 
    29 int main()
    30 {
    31     int n,num=1;
    32     prime[2]=prime[3]=prime[5]=prime[7]=prime[11]=prime[13]=prime[17]=prime[19]=
    33     prime[23]=prime[29]=prime[31]=prime[37]=1;
    34     path[1]=1;
    35     while(scanf("%d",&n)!=EOF)
    36     {
    37         printf("Case %d:\n",num++);
    38         if(n%2==0)//当n为奇数时,肯定不符合条件;
    39         {
    40             memset(used,0,sizeof(used));
    41             DFS(2,n);//从第二个数开始搜索
    42         }
    43         printf("\n");
    44     }
    45 }
    功不成,身已退
  • 相关阅读:
    跳跃表原理
    ThreadLocal
    Innodb中的事务隔离级别和锁的关系
    线程池拒绝策略
    vue 的 nextTick 原理
    Git 的基本操作
    JavaScript 的运行机制
    实现一个react系列三:生命周期
    实现一个react系列二:渲染组件
    实现一个react系列一:JSX和虚拟DOM
  • 原文地址:https://www.cnblogs.com/dongsheng/p/2545673.html
Copyright © 2011-2022 走看看