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): 30395    Accepted Submission(s): 13525


    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
     
    //第一次写dfs,既然发现和小白上的代码一样,开心
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    int prime[]= {0,0,1,1,0,1,0,1,0,0,0,
                  1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,
                  0,0,1,0,1,0,0,0,0,0,1,0,0,0
                 };//方便判断一个数是否素数
    int flag[25];//标志数组
    int c[25];//结果数组
    int n;
    void dfs(int cur)
    {
        int i,j;
        if(cur==n+1&&prime[1+c[cur-1]])//别忘记第一个数和最后一个数的和也应该是素数
        {
            for(j=1; j<n; j++) printf("%d ",c[j]);
            printf("%d
    ",c[n]);
        }
        else for(i=2; i<=n; i++)//每个数都应是从2——n选择
                if(!flag[i]&&prime[i+c[cur-1]])//是否满足条件
                {
                    c[cur]=i;//尝试把i作为第cur个满足条件的数
                    flag[i]=1;//设置使用标志
                    dfs(cur+1);
                    flag[i]=0;//谨记清除标记
                }
    }
    int main()
    {
        int k=1;
        while(~scanf("%d",&n))
        {
            printf("Case %d:
    ",k++);
            memset(flag,0,sizeof(flag));
            c[1]=1;
            dfs(2);//第一个数就是1,从第二个数开始
            printf("
    ");
        }
    }
    不知什么鬼,G++提交超时,c++ 256ms
  • 相关阅读:
    idea中使用git进行clone、分支切换、pull、push等
    grep参数说明及常用用法(转)
    性能01篇-如何胜任性能测试工程师岗位
    2016年7款最流行的Java框架
    Python程序员都会喜欢的6个库
    web开发者最有用的10个Python包
    web开发的10款Python框架
    python的十个技巧
    Python的接口测试框架实例
    调试支付宝接口?
  • 原文地址:https://www.cnblogs.com/orchidzjl/p/4352305.html
Copyright © 2011-2022 走看看