zoukankan      html  css  js  c++  java
  • UVA 524 素数环 【dfs/回溯法】

    Description

     
    A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1,2,3,...,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 <= 16)

    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.

     
    You are to write a program that completes above process.

    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


    【代码】:
    /*素数环*/
    #include <bits/stdc++.h>
    using namespace std;
    int n,prime[1005]={1},v[1005],a[1005];
    
    void get_prime()
    {
        int m=sqrt(2*n+0.5);//环-倍增
        memset(prime,1,sizeof(prime));//0为素数
        prime[0]=prime[1]=0;//非素数
        for(int i=2;i<=m;i++)
        {
            if(prime[i])//素数
            {
                for(int j=i+i;j<=2*n;j+=i)
                {
                    prime[j]=0;//非素数
                }
            }
        }
    }
    
    void dfs(int cur)
    {
        if(cur == n && prime[ a[0]+a[n-1] ])
        {
            for(int i=0; i<n; i++)
            {
                 printf("%d%c", a[i], i == n - 1 ? '
    ' : ' ');
            }
           // printf("
    ");
        }
        else
        {
            for(int i=2; i<=n; i++)
            {
                if( !v[i] && prime[ i + a[cur-1] ] )
                {
                    a[cur] = i;
                    v[i]=1;
                    dfs(cur+1);
                    v[i]=0;
                }
            }
        }
    }
    int main()
    {
        scanf("%d",&n);
        //初始化
        memset(v,0,sizeof(v));
        a[0]=1;
    
        get_prime();
        dfs(1);
    }
  • 相关阅读:
    关于binary log一点总结[转]
    使用mysql索引技巧及注意事项
    优化php性能的一点总结
    html静态页面实现微信分享思路
    MySql字符串函数使用技巧
    Oracle计算时间差函数
    oracle10g获取Date类型字段无时分秒解决办法!
    Oracle常用函数
    COALESCE操作符
    关于null的操作
  • 原文地址:https://www.cnblogs.com/Roni-i/p/8056995.html
Copyright © 2011-2022 走看看