zoukankan      html  css  js  c++  java
  • HDU-1016 Prime Ring 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


    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int d[30], num[30], n;
    bool func(int);
    
    int main(void)
    {
        void dfs(int);
        int times = 0;
        
        while(cin >> n)
        {
            times++;
            cout << "Case " << times << ':' << endl;
            memset(d, 0, sizeof(d));
            d[1] = 1;
            num[0] = 1;
            dfs(1);
            cout << endl;
        }
        
        
        return 0;
    }
    
    
    void dfs(int t)
    {
        if(t == n)
        {
            if(!func(num[n-1]+1))
                return;
            
            for(int i = 0; i < n-1; i++)
            {
                cout << num[i] << ' ';
            }
            cout << num[n-1] << endl;
            return;
        }
        
        for(int i = 2; i <= n; i++)
        {
            if(!d[i] && func(i+num[t-1]))
            {
                num[t] = i;
                d[i] = 1;
                dfs(t+1);
                d[i] = 0;
            }
        }
        return ;
    }
    
    
    bool func(int a)
    {
        int q = sqrt(a);
        
        for(int i = 2; i <= q; i++)
        {
            if(a%i == 0)
                return false;
        }
        return true;
    }
    
  • 相关阅读:
    关于Linux 上建立生成/添加SSH公钥
    sql随机插入数据--记录
    centos 安装搜狗
    centos yum命令找不到包
    命令行改为图形界面
    CentOS7l联网
    .net mvc 框架实现后台管理系统 3
    .net mvc 框架实现后台管理系统 2
    .net mvc 框架实现后台管理系统
    爬取猫眼数据
  • 原文地址:https://www.cnblogs.com/limyel/p/6683235.html
Copyright © 2011-2022 走看看