zoukankan      html  css  js  c++  java
  • HDU-1016 Prime Ring Rroblem (dfs)

    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. 

     

    Inputn (0 < n < 20). 
    OutputThe 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<bits/stdc++.h>
    using namespace std;
    int x,mark[25],a[25];
    int check(int n){
        if(n==1)
            return 0;
        if(n==2)
            return 1;
        for(int i=2;i<n;i++)
            if(n%i==0)
            return 0;
        return 1;
    }
    void dfs(int step){
        if(step>x&&check(mark[x]+mark[1])){
            int i;
            for(i=1;i<=x-1;i++)
                cout<<mark[i]<<" ";
            cout<<mark[i]<<endl;
        }
        for(int i=2;i<=x;i++){
            mark[step]=i;
            if(check(mark[step]+mark[step-1])&&!a[i]){
                a[i]=1;
                dfs(step+1);
                a[i]=0;
            }
        }
    }
    int main()
    {
        int k=1;
        while(cin>>x){
            cout<<"Case "<<k++<<":"<<endl;
            memset(a,0,sizeof(a));
            mark[1]=1;
            dfs(2);
            cout<<endl;
        }
        return 0;
    }
    

      

  • 相关阅读:
    某个账号微信的微信朋友圈内容抓取 部分好友内容抓取
    密钥登录
    CPU处理器架构和工作原理浅析
    perl 安装Net::ZooKeeper
    perl 安装Net::ZooKeeper
    thinkphp 常用的查询
    thinkphp 常用的查询
    ThinkPHP 3.1.2 模板中的基本语法<2>
    ThinkPHP 3.1.2 模板中的基本语法<2>
    perl post 带上请求头
  • 原文地址:https://www.cnblogs.com/zzzying/p/7256239.html
Copyright © 2011-2022 走看看