zoukankan      html  css  js  c++  java
  • [HDOJ1016]Prime Ring Problem

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1016

    原题:

    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.

    输入N个数字,求1到N这N个数字连成环以后两两相加均为素数的所有情况。

    非常经典的DFS题。

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <cmath>
    using namespace std;
    int n;
    int cir[21];
    int prime[41];
    int vis[21];
    int isPrime(int x)
    {
        int i;
        int sqx = sqrt((float)x);
        for(i = 2; i <= sqx; i++)
        {
            if(x % i == 0)
            {    
                return 0;
            }
        }
        return 1;
    }
    
    void dfs(int x)
    {
        int i;
        if(x == n && prime[cir[1]+cir[n]])    //make a circle
        {
            for(i = 1; i < n; i++)
            {
                printf("%d ", cir[i]);
            }
            printf("%d
    ", cir[n]);
            return ;
        }
        for(i = 2; i <= n; i++)
        {
            if(vis[i] == 0 && prime[cir[x]+i])
            {
                cir[x+1] = i;
                vis[i] = 1;
                dfs(x+1);
                vis[i] = 0;    //reset
            }
        }
    }
    
    int main()
    {
        int i, Case = 1;
        for(i = 1; i < 41; i++)    //list primes.
        {
            if(isPrime(i))
            {
                prime[i] = 1;
            }
        }
    
        while(scanf("%d", &n) != EOF && n)
        {
            printf("Case %d:
    ", Case++);
            memset(vis, 0, sizeof(vis));
            cir[1] = 1;
            vis[1] = 1;
            dfs(1);
            printf("
    ");
        }
        return 0;
    }
  • 相关阅读:
    大型网站架构系列:负载均衡详解(1)
    转:构建高并发高可用的电商平台架构实践
    转:RBAC权限控制
    小型电商网站的架构
    中小型电子商务网站架构
    装饰器在类中的实现
    使用MySQLdb操作Mysql数据库
    unicode转中文以及str形态的unicode转中文
    了解Python内存管理机制,让你的程序飞起来
    多线程初级入门学习
  • 原文地址:https://www.cnblogs.com/kirai/p/4515941.html
Copyright © 2011-2022 走看看