poj 2513 -- Colored Sticks ( Trie + 并查集 + 欧拉 )

WA了很久的一道题了,今天终于过了

判断条件有两个

1 、出现次数为奇数的颜色<=2 

2 、判断图是否连通

用Trie处理效率较高,判断连通可以将颜色映射成数字用并查集


# 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 ;

struct Dic
{
    int id ;
    int vis ;
    int next [ 30 ] ;
} dic [ 3000000 ] ;
int cnt ;
int pre [ 510000 ] ;
int top ;

int find ( int x )
{
    if ( pre [ x ] != x )
        pre [ x ] = find ( pre [ x ] ) ;
    return pre [ x ] ;
}

void Union ( int x , int y )
{
    pre [ find ( x ) ] = find ( y ) ;
}

int addword ( char t [ ] )
{
    int num = 0 ;
    int len = strlen ( t ) ;
    for ( int i = 0 ; i < len ; i ++ )
    {
        int tmp = t [ i ] - 'a' ;
        if ( dic [ num ] . next [ tmp ] == 0 )
        {
            dic [ num ] . next [ tmp ] = cnt ;
            num = cnt ++ ;
        }
        else
            num = dic [ num ] . next [ tmp ] ;
    }
    dic [ num ] . vis ++ ;
    if ( dic [ num ] . vis == 1 )
    {
        dic [ num ] . id = top ++ ;
    }
    return dic [ num ] . id ;
}

int findword ( char * t )
{
    int num = 0 ;
    int len = strlen ( t ) ;
    for ( int i = 0 ; i < len ; i ++ )
    {
        int tmp = t [ i ] - 'a' ;
        if ( dic [ num ] . next [ tmp ] == 0 )
            return false ;
        else
            num = dic [ num ] . next [ tmp ] ;
    }
    return dic [ num ] . id ;
}

int main ( )
{
    cnt = 1 ;
    top = 1 ;
    for ( int i = 1 ; i < 510000 ; i ++ )
        pre [ i ] = i ;
    char s [ 12 ] , t [ 13 ] ;
    while ( scanf ( "%s%s" , s , t ) != EOF )
    {
        int x = addword ( s ) ;
        int y = addword ( t ) ;
        Union ( x , y ) ;
    }
    int flag = 1 ;
    int sum = 0 ;
    for ( int i = 1 ; i < cnt ; i ++ )
    {
        if ( dic [ i ] . vis % 2 )
            sum ++ ;
    }
    if ( sum > 2 )
        flag = 0 ;
    if ( flag == 0 )
        cout << "Impossible" << endl ;
    else
    {
        for ( int i = 2 ; i < top ; i ++ )
            if ( find ( i ) != find ( 1 ) )
                flag = 0 ;
        if ( flag )
            cout << "Possible" << endl ;
        else
            cout << "Impossible" << endl ;
    }
}


你可能感兴趣的:(poj 2513 -- Colored Sticks ( Trie + 并查集 + 欧拉 ))