poj 2001 -- Shortest Prefixes ( 字典树 )

给出一个字典 , 输出每一个单词唯一的最短前缀 

数据不是很大, 排序暴力应该也可以处理 ,我这里用了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 ;

char s [ 1100 ] [ 21 ] ;

struct Dic
{
    int time ;       //所经过的次数
    int next [ 30 ] ;
} dic [ 1000000 ] = { 0 } ;
int cnt ;

void addword ( char * s )
{
    int len = strlen ( s ) ;
    int num = 0 ;
    for ( int i = 0 ; i < len ; i ++ )
    {
        int c =  s [ i ] - 'a' ;
        if ( dic [ num ] . next [ c ] )
        {
            num = dic [ num ] . next [ c ] ;
            dic [ num ] . time ++ ;
        }
        else
        {
            dic [ num ] . next [ c ] = cnt ;
            num = cnt ++ ;
            dic [ num ] . time ++ ;
        }
    }
}

void findword ( char * s )
{
    int len = strlen ( s ) ;
    int num = 0 ;
    for ( int i = 0 ; i < len ; i ++ )
    {
        int c =  s [ i ] - 'a' ;
        if ( dic [ num ] . time == 1 )
            break ;
        putchar ( s [ i ] ) ;
        num = dic [ num ] . next [ c ] ;
    }
}

int main ( )
{
    cnt = 1 ;
    int n = 0 ;
    while ( gets ( s [ n ] ) )
    {
        addword ( s [ n ++ ] ) ;
    }
    dic [ 0 ] . time = n ;
    for ( int i = 0 ; i < n ; i ++ )
    {
        printf ( "%s " , s [ i ] ) ;
        findword ( s [ i ] ) ;
        printf ( "\n" ) ;
    }
}


你可能感兴趣的:(poj 2001 -- Shortest Prefixes ( 字典树 ))