poj 3842 -- An Industrial Spy ( 全排列 )

用递归写了个全排列,还好 , 素数处理我是先打了个1000W 的素数表 , 测了一下打标大约500ms , 还不如直接暴力算素数  。。。。。

# include <cstdio>
# include <iostream>
# include <set>
# include <map>
# include <vector>
# include <list>
# include <queue>
# include <stack>
# include <cstring>
# include <string>
# include <cstdlib>
# include <cmath>
# include <algorithm>

using namespace std ;

bool prime [ 10000001 ] = { 0 } ;
char s [ 10 ] ;
int len ;

void getprim ( )           //打素数表 , 没用到
{
    for ( int i = 2 ; i <= 10000000 ; i ++ )
        prime [ i ] = 1 ;
    for ( int i = 2 ; i <= 10000000 ; i ++ )
    {
        if ( prime [ i ] == 0 )
            continue ;
        for ( int j = 2 ; i * j <= 10000000 ; j ++ )
            prime [ i * j ] = 0 ;
    }
}

bool isprime ( int n )
{
    int end = sqrt ( n ) ;
    if ( n == 0 || n == 1 )
        return false ;
    if ( n == 2 )
        return true ;
    for ( int i = 2 ; i <= end ; i ++ )
        if ( n % i == 0 )
            return false ;
    return true ;
}

bool flag [ 10 ] ;
int ans ;

void dfs ( int sum , int pos )
{
    if ( isprime ( sum ) )
    {
        ans ++ ;
    }
    if ( len == pos )
    {
        return ;
    }
    bool f2 [ 10 ] = { 0 } ;
    for ( int i = 0 ; i < len ; i ++ )
    {
        int t = s [ i ] - '0' ;
        if ( ! flag [ i ] && ! f2 [ t ] )
        {
            if ( pos == 0 && t == 0 )
                continue ;
            f2 [ t ] = 1 ;
            flag [ i ] = 1 ;
            dfs ( sum * 10 + t , pos + 1 ) ;
            flag [ i ] = 0 ;
        }
    }
}

int main ( )
{
    //getprim ( ) ;
    int t ;
    scanf ( "%d" , & t ) ;
    getchar ( ) ;
    while ( t -- )
    {
        memset ( flag , 0 , sizeof ( flag ) ) ;
        gets ( s ) ;
        len = strlen ( s ) ;
        ans = 0 ;
        dfs ( 0 , 0 ) ;
        printf ( "%d\n" , ans ) ;
    }
}


你可能感兴趣的:(poj 3842 -- An Industrial Spy ( 全排列 ))