zoukankan      html  css  js  c++  java
  • zstu4028——DFS+回溯——素数和环

    Description

    把前n个正整数摆成1个环,如果环中所有相邻的2个数之和都是1个素数,该环称为1个n项素数和环。 输入1个整数n,输出共有多少种

    Input

    输入一个正整数n

    Output

    输出环的个数,要求环的第一个数字是1

    Sample Input

    4

    Sample Output

    2

    HINT

    大意:回溯,要会写dfs得到全排列

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    const int maxn = 66666;
    int vis[maxn];
    int a[maxn];
    void dfs(int step)
    {
        if(step == n + 1){
            for(int i = 1; i <=  n; i++)
                printf("%d",a[i]);
                return ;
        }
        else {
            for(int i = 1; i <= n ; i++){
                if(!vis[i]){
                    vis[i] = 1;
                    a[step] = i;
                    dfs(step+1);
                    vis[i] = 0;
                }
            }
        }
    }
    

     AC代码

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    const int maxn = 666666;
    int vis[maxn];
    int n,cout;
    int a[maxn];
    int prim(int n){
        int i;
        for( i = 2; i*i <= n ;i++){
            if(n%i == 0)
                break;
        }
        if(i*i > n)
        return 1;
         return 0;
    }
    void dfs(int step)
    {
        if(step == n+1){
            int i;
            //for(int j = 1; j <= n ;j++)
            //    printf("%d",a[j]);
            //    puts("");
            for( i = 1; i <= n ;i++){
                int x = a[i],y = a[i+1];
                if(i == n){
                    y = a[1];
                }
                if(prim(x+y) == 0){
                    break;
                }
            }
            if(i > n) {
            //for(int i = 1; i <= n ;i++)
            //    printf("%d",a[i]);
           // puts("");
           // printf("%d %d
    ",a[4]+a[5],prim(a[4]+a[5]));
            cout++;
     
            }
        }
        for(int i = 2; i <= n ; i++){
            if(!vis[i]){
                vis[i] = 1;
                a[step] = i;
                dfs(step+1);
                vis[i] = 0;
            }
        }
    }
    int main()
    {
        a[1] = 1;
        while(~scanf("%d",&n)){
            if(n%2 == 1)
                printf("0
    ");
            else {
            cout = 0;
            dfs(2);
            printf("%d
    ",cout);
            }
        }
        return 0;
    }
     
    

      

  • 相关阅读:
    Python十大经典算法之选择排序
    在js中修改样式带 !important 的样式
    vscode 使用 ejs 语法有红色错误提示线
    mysql 报 'Host ‘XXXXXX’ is blocked because of many connection errors'
    字符编码
    Canal.adapter报错
    Windows 域控配置时间同步
    Docker清理日志脚本
    Docker快速部署clickhouse
    Windows批处理一键添加hosts文件
  • 原文地址:https://www.cnblogs.com/zero-begin/p/4514972.html
Copyright © 2011-2022 走看看