zoukankan      html  css  js  c++  java
  • 素数环(简单搜索)

     

    Prime Ring Problem

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


    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的奇数的话就不存在素数环,在测试数据含有大量奇数时加以判断可节省时间
     
     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 using namespace std;
     5 int a[50],b[21],test[21];
     6 int n;
     7 void prime()
     8 {
     9     int i,j;
    10     for(i=2;i<=50;i++)
    11     {
    12         for(j=2;j<=i/2;j++)
    13             if(i%j==0)
    14                 break;
    15         if(j==(i/2+1))
    16             a[i]=1;
    17         else
    18             a[i]=0;
    19     }
    20 }
    21 void dfs(int s)
    22 {
    23     int i,j,k;
    24     if(s==n+1&&a[b[n]+1])
    25     {
    26         for(i=1;i<n;i++)
    27             cout<<b[i]<<" ";
    28         cout<<b[n]<<endl;
    29     }
    30     else for(i=2;i<=n;i++)
    31         if(a[b[s-1]+i]&&!test[i])
    32         {
    33             b[s]=i;
    34             test[i]=1;
    35             dfs(s+1);
    36             test[i]=0;
    37         }
    38 }
    39 int main()
    40 {
    41     b[1]=1;
    42     prime();
    43     int i,j;
    44     while(cin>>n&&n)
    45     {
    46         cout<<"Case "<<j<<":"<<endl;
    47         memset(test,0,sizeof(test));
    48         dfs(2);
    49         cout<<endl;
    50         j++;
    51     }
    52 }
  • 相关阅读:
    转:IOCP在网络应用中常见错误分析
    Ext.Button的禁用
    Excel连接字符串
    从表单为实体对象赋值
    根据指定类型创建数组
    Ext.GridPanel数据显示不正确
    vue 记事本
    杂谈(一)
    推荐《程序设计的 Top 10 做与不做》和《关于编程,鲜为人知的真相》
    (转)黄鸣博客:警惕29岁现象
  • 原文地址:https://www.cnblogs.com/a1225234/p/4955547.html
Copyright © 2011-2022 走看看