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

    Prime Ring Problem

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


    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
     
    思路:
    简单的DFS,做过突然想温习一下,旧题新写

    代码:
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<cstdlib>
    #include<cmath>
    #include<string>
    using namespace std;
    const int MAXN=21;
    bool flag[MAXN];
    int ans[MAXN];
    int total=0;
    int t=1;
    int N;
    bool check(int x, int y)
    {
        x+=y;
        int i=2;
        while(i<=sqrt(x)&&x%i)
        {
            i++;
        }
        if(i>sqrt(x))
            return true;
        return false;
    }
    void print()
    {
        printf("%d",ans[1]);
        for(int i=2;i<=N;i++)
        {
            printf(" %d",ans[i]);
        }
        printf("
    ");
    }
    void dfs(int num)
    {
        for(int i=2;i<=N;i++)
        {
            if(check(ans[num-1],i)&&!flag[i])
            {
                ans[num]=i;
                flag[i]=true;
                if(num==N)
                {
                    if(check(ans[num],ans[1]))
                        print();
                }
                else
                {
                    dfs(num+1);
                }
                flag[i]=false;
            }
        }
    }
    int main()
    {
        while(scanf("%d",&N)!=EOF)
        {
            memset(flag,false,sizeof(flag));
            printf("Case %d:
    ",t);
            ans[1]=1;
            dfs(2);
            printf("
    ");
            t++;
        }
        return 0;
    }
    


  • 相关阅读:
    函数基础
    全局变量与类似配置文件的模块文件
    global语句(python学习手册422页)
    作用域实例
    变量名解析:LEGB原则
    作用域
    第三方库安装方法
    s[-1]和s[len(s)-1]
    查找特定后缀的文件
    logging日志管理-将日志写入文件
  • 原文地址:https://www.cnblogs.com/lemonbiscuit/p/7776017.html
Copyright © 2011-2022 走看看