zoukankan      html  css  js  c++  java
  • ACM HDU 1016 Prime Ring Problem

    Prime Ring Problem

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


    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
     

    Source
     

    Recommend
    JGShining
     
     
     
    深搜,简单题:
    看代码,还可以优化,尤其是判断素数的时候,可以用筛选法,或者直接列出40内的素数:
    #include<stdio.h>
    #include
    <cmath>
    #include
    <string.h>
    int a[21];
    int used[21];
    int n;
    bool prime(int n)
    {
    int m=(int)sqrt(n);
    int i;
    for(i=2;i<=m;i++)
    if(n%i==0)break;
    if(i>m)return true;
    else return false;
    }
    void dfs(int k)
    {
    if(k==n+1)
    {
    if(prime(a[1]+a[n]))
    {
    for(int i=1;i<n;i++)printf("%d ",a[i]);
    printf(
    "%d\n",a[n]);
    }
    }
    else
    {
    for(int i=1;i<=n;i++)
    {
    if(used[i]==0&&prime(i+a[k-1]))
    {
    used[i]
    =1;
    a[k]
    =i;
    dfs(k
    +1);
    used[i]
    =0;
    }

    }
    }
    }
    int main()
    {
    int i=1;
    while(scanf("%d",&n)!=EOF)
    {
    memset(used,
    0,sizeof(used));
    a[
    1]=1;used[1]=1;
    printf(
    "Case %d:\n",i++);
    dfs(
    2);
    printf(
    "\n");

    }
    return 0;
    }

  • 相关阅读:
    百度网盘下载太慢,试试阿里云网盘?
    linux使用过程中遇到的常见问题
    vscode设置护眼色
    为什么程序员互相之间不能透露薪水?
    机器学习:支持向量机(SVM)
    Java多线程总结(三)
    Java多线程总结(二)
    Java多线程总结(一)
    8.多线程--避免活跃性危险
    7.多线程--线程池的使用
  • 原文地址:https://www.cnblogs.com/kuangbin/p/2119917.html
Copyright © 2011-2022 走看看