zoukankan      html  css  js  c++  java
  • Uva 552 Prime Ring Problem(dfs)

    题目链接:Uva 552

    思路分析:时间限制为3s,数据较小,使用深度搜索查找所有的解。

     

    代码如下:

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    const int MAX_N = 20;
    int n;
    int A[MAX_N], vis[MAX_N];
    
    int is_prime( int n )
    {
        if ( n == 2 )
            return true;
    
        for ( int i = 2; i * i <= n; ++i )
        if ( n % i == 0 )
            return false;
    
        return true;
    }
    
    void dfs( int cur )
    {
        if ( cur == n && is_prime( A[0] + A[n - 1] ) )
        {
            int i = 0;
    
            for ( i = 0; i < n - 1; ++i )
                printf( "%d ", A[i] );
            printf( "%d", A[i] );
            printf( "
    " );
        }
        else
        {
            for ( int i = 2; i <= n; ++i )
            {
                if ( !vis[i] && is_prime( i + A[cur - 1] ) )
                {
                    A[cur] = i;
                    vis[i] = 1;
                    dfs( cur + 1 );
                    vis[i] = 0;
                }
            }
        }
    }
    
    int main( )
    {
        int count = 1;
    
        while ( scanf( "%d", &n ) != EOF )
        {
            if ( count != 1 )
                printf( "
    " );
    
            A[0] = 1;
            memset( vis, 0, sizeof( vis ) );
            printf( "Case %d:
    ", count++ );
            dfs( 1 );
        }
    
        return 0;
    }
  • 相关阅读:
    todo-list
    codeforces 794 (#414 DIV1+DIV2)
    2018bnu校赛总结
    codeforces 743D
    HDU-2196 Computer (树形DP)
    HDU- 1005 Number Sequence(矩阵快速幂)
    HDU- 4000 Fruit Ninja(树状数组)
    codeforces 505C
    codeforces 286B
    codeforces 3D
  • 原文地址:https://www.cnblogs.com/tallisHe/p/4027881.html
Copyright © 2011-2022 走看看