zoukankan      html  css  js  c++  java
  • [CODEVS] 1031 质数环

    1031 质数环 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 题目描述 Description
    一个大小为N(N<=17)的质数环是由1到N共N个自然数组成的一个数环,数环上每两个相邻的数字之和为质数。如下图是一个大小为6的质数环。为了方便描述,规定数环上的第一个数字总是1。如下图可用1
    4 3 2 5 6来描述。若两个质数环,数字排列顺序相同则视为本质相同。现在要求你求出所有本质不同的数环。

    输入描述 Input Description

    只有一个数N,表示需求的质数环的大小。如:

    输出描述 Output Description 每一行描述一个数环,如果有多组解,按照字典序从小到大输出。如:

    样例输入 Sample Input 6

    样例输出 Sample Output 1 4 3 2 5 6

    1 6 5 2 3 4

    数据范围及提示 Data Size & Hint n<=17

    两个问题:
    1.输出不重复的序列
    2.TLE

    • 不重复好说,保证第一个数是1就行,开始是在print函数里写判断,但还是重复生成了很多不是1开头的序列,答案正确,但大数据TLE。之后在dfs的条件里写,有些好转,还是TLE.

    • 又想到打表,素数最多也就17+17=34个,果然快了好多。

    #include<iostream>
    #include<cmath>
    using namespace std;
    int a[21];
    bool b[21];
    int n;
    int prime[40] = {
        0, 1, 1, 1, 0, 1, 0,
        1, 0, 0, 0, 1, 0, 1,
        0, 0, 0, 1, 0, 1, 0,
        0, 0, 1, 0, 0, 0, 0,
        0, 1, 0, 1, 0, 0, 0,
        0, 0, 1, 0 ,1
    } ;
    
    inline bool pd(int x,int y) {
        return prime[x+y];
    }
    
    void print() {
        cin.sync_with_stdio(false);
        cin.tie(0);
        if(a[1]==1) {
            for(int i=1; i<=n; i++) cout<<a[i]<<" ";
            cout<<endl;
        }
    }
    
    void dfs(int dp) {
    
        int i;
        for(i=1; i<=n; i++) {
            if(pd(a[dp-1],i)&&!b[i]) {
    
                a[dp]=i;
                b[i]=1;
                if(a[1]!=1) return;/////////////
                if(pd(a[dp],a[1])&&dp==n) print();
                else dfs(dp+1);
                b[i]=0;
            }
        }
    }
    
    
    int main() {
        cin>>n;
        dfs(1);
    }

    本文来自博客园,作者:GhostCai,转载请注明原文链接:https://www.cnblogs.com/ghostcai/p/9247553.html

  • 相关阅读:
    制造者为什么重要
    归因理论
    初创业谨记有三法宝:顶梁柱、现金牛、北极星
    华特迪士尼语录
    说好一个创业故事的5个步骤
    接口
    抽象类_模板方法设计模式
    抽象类与抽象方法
    非static和static初始化块
    单例设计模式
  • 原文地址:https://www.cnblogs.com/ghostcai/p/9247553.html
Copyright © 2011-2022 走看看