zoukankan      html  css  js  c++  java
  • HDU 1016 Prime Ring Problem(全排列)

    题目链接:https://vjudge.net/problem/HDU-1016

    题目大意:让你构造一个n个数组成的环,每两个相邻的数之合都是素数

    只要用递归算出来所有符合条件的全排列即可

    #include<set>
    #include<map>
    #include<stack>
    #include<queue>
    #include<cmath>
    #include<cstdio>
    #include<cctype>
    #include<string>
    #include<vector>
    #include<climits>
    #include<cstring>
    #include<cstdlib>
    #include<iostream>
    #include<algorithm>
    #define endl '\n'
    #define max(a, b) (a > b ? a : b)
    #define min(a, b) (a < b ? a : b)
    #define mst0(a) memset(a, 0, sizeof(a))
    #define mstnil(a) memset(a, -1, sizeof(a))
    #define mstinf(a) memset(a, 0x3f3f3f3f, sizeof(a))
    #define IOS ios::sync_with_stdio(false)
    #define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
    using namespace std;
    typedef long long ll;
    typedef pair<int, int> P;
    const double pi = acos(-1.0);
    const double eps = 1e-7;
    const ll MOD = 1e9+7;
    const int INF = 0x3f3f3f3f;
    const int NIL = -1;
    template<typename T> ll read(T &x){
        x = 0; char ch = getchar(); ll fac = 1;
        while(!isdigit(ch)) { if(ch == '-') fac*=-1; ch = getchar(); }
        while(isdigit(ch)) { x = x*10+ch-48; ch = getchar(); } x*=fac; return x;
    }
    const int maxn = 1e3+10;
    int prime[maxn], kase, nums[maxn], vis[maxn];
    bool isprime[maxn] = {1, 1};
    void primeMaker() {
        for (int i = 2; i<maxn; ++i) {
            if (!isprime[i])
                prime[kase++] = i;
            for (int j = 0; j<kase && i*prime[j] < maxn; ++j) {
                isprime[prime[j]*i] = true;
                if (!(i%prime[j])) break;
            }
        }
    }
    void dfs(int pos, int n) {
        if (pos > n && !isprime[nums[1]+nums[n]])
            for (int i = 1; i<=n; ++i)
                printf(i == n ? "%d\n" : "%d ", nums[i]);
        else if (pos > n) return;
        else {
            for (int i = 2; i<=n; ++i)
                if (!vis[i] && !isprime[i+nums[pos-1]]) {
                    nums[pos] = i;
                    vis[i] = true;
                    dfs(pos+1, n);
                    vis[i] = false;
                }
        }
    }
    int main(void) {
        int n, ccase = 1;
        primeMaker();
        while(~scanf("%d", &n)) {
            printf("Case %d:\n", ccase++);
            mst0(vis);
            nums[1] = 1;
            vis[1] = true;
            dfs(2, n);
            putchar(endl);
        }
        return 0;
    }
  • 相关阅读:
    两种接口传送数据协议(xml和json)
    两种访问接口的方式(get和post)
    myeclipse 编写java代码提示 dead code 原因
    svn文件冲突,树冲突详解
    linux操作提示:“Can't open file for writing”或“operation not permitted”的解决办法
    embed标签属性
    程序员必读的书刊收藏
    python实现冒泡排序和快速排序
    python简单词频统计
    Qt出现堆溢出(Error Code -1073741823)
  • 原文地址:https://www.cnblogs.com/shuitiangong/p/12384775.html
Copyright © 2011-2022 走看看