• A


    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
     
     
     
    这道题是输入n,让你找从1到n这些整数组成的 相邻的数的和为素数的环有几个,从1开始顺时针输出
     
    注意题目要求输出一行Case n:(看清这个冒号啊~~~~~~~~当时没看到一直wr),而且Print a blank line after each case. ,(也没看清这个,真是惨啊~~~~)
    减小复杂度的技巧:题中出现的最大素数为37,所以不必每种情况都再算一次相邻的数的和是不是素数,这样可能超时,而且dfs本来复杂度就挺高的,可以用pri[i]表记i是否为素数,
     
     
    #include <cstdio>
    #include <string.h>
    #include <math.h>
    int num[25], t, n, now; //num记录最后选中的数
    bool vis[25], pri[40];//pri[i] = 1表示i为素数,pri[i] = 0表示i不是素数
    bool prime(int y) //bool类型的函数,这样就不用定义变量作为返回值了
    {
        for(int i = 2; i <= sqrt(y); i++)
        {
            if(y % i == 0)
                return false;
        }
        return true;
    }
    void dfs(int now, int t) //已经找到t个数了,第t个数为now,也就是当前数为now,进入dfs也就是找第t+1个数
    {
        if(t == n) //该找第n个数时,看看第n个数和第一个数相加是否是素数,因为组成的是个环,ps:一定记得!!!
        {
            if(pri[now+1])
            {
                printf("1");
                for(int i = 2; i <= n; i++)
                    printf(" %d", num[i]);
                printf("
    ");
            }
            return;
        }
    
        for(int i = 2; i <= n; i++)
        {
            if(vis[i] && pri[i+now])
            {
                vis[i] = 0;
                num[t+1] = i;
                dfs(i, t+1);
                vis[i] = 1;
            }
        }
    
    }
    int main()
    {
        int cnt = 1;
        while(~scanf("%d", &n))
        {
            memset(vis, 1, sizeof(vis));
            for(int i = 3; i < 40; i++)
            {
                if(prime(i))
                    pri[i] = 1;
                else
                    pri[i] = 0;
            }
            printf("Case %d:
    ", cnt++); //当时忘了冒号!!!!!!!!!!!!!!!!!!!!!!!!!!惨啊~~~~
            num[1]=1; vis[1] = 0;
            dfs(1, 1);
            printf("
    ");//当时也忘了每个案例之间也要输出空行~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~!!!!!!!!!!嗷~~~
        }
        return 0;
    }
     
  • 相关阅读:
    关闭程序 提示 C#
    瀑布流判断加载分页条件
    移动端模板
    js 获取地址栏参数
    原生js倒计时和显示当前时间
    根据日期判断事件
    多个tab切换传参
    h5的api dom全屏展示
    git配置ssh
    git创建分支与合并分支
  • 原文地址:https://www.cnblogs.com/rain-1/p/4798430.html
Copyright © 2020-2023  润新知