poj 2001 trie
第一道trie
还需要写题来建立自己的代码习惯。
1 #include <cstdio> 2 #include <vector> 3 #include <algorithm> 4 #define maxn 20010 5 using namespace std; 6 7 struct node { 8 char v; 9 int sz; 10 bool isword, mark; 11 node *son[26], *pre; 12 }pool[maxn], *tail=pool, *null=pool; 13 14 char temp[100]; 15 struct Trie { 16 node *root; 17 vector<node*> stk; 18 node* newnode( node *p, char v ) { 19 node *nd = ++tail; 20 nd->sz = 0; 21 nd->v = v; 22 nd->isword = nd->mark = false; 23 nd->pre = p; 24 for( int i=0; i<26; i++ ) nd->son[i] = null; 25 return nd; 26 } 27 void insert( const char *str ) { 28 if( !root ) root=newnode(null,'^'); 29 node *nd=root; 30 while(1) { 31 if( *str ) { 32 if( nd->son[*str-'a']==null ) nd->son[*str-'a']=newnode(nd,*str-'a'); 33 nd->sz++; 34 nd = nd->son[*str-'a']; 35 str++; 36 } else { 37 nd->isword = true; 38 stk.push_back( nd ); 39 return; 40 } 41 } 42 } 43 void make_mark( node *nd ) { 44 if( nd->isword ) { 45 nd->mark = true; 46 for( int i=0; i<26; i++ ) 47 if( nd->son[i]!=null ) make_mark(nd->son[i]); 48 } else if( nd->sz==1 ) { 49 nd->mark = true; 50 } else { 51 for( int i=0; i<26; i++ ) 52 if( nd->son[i]!=null ) make_mark(nd->son[i]); 53 } 54 } 55 char *get( node *bt ) { 56 while( !bt->mark ) bt=bt->pre; 57 int i; 58 for( i=0; bt!=root; i++,bt=bt->pre ) 59 temp[i] = bt->v+'a'; 60 temp[i] = 0; 61 reverse( temp, temp+i ); 62 return temp; 63 } 64 void print( node *nd ) { 65 fprintf( stderr, "nd %d ch %c mark %d\n", nd-pool, nd->v+'a', nd->mark ); 66 for( int i=0; i<26; i++ ) 67 if( nd->son[i]!=null ) print(nd->son[i]); 68 } 69 }T; 70 71 void pt( char *st ) { 72 fprintf( stderr, "%s\n", st ); 73 } 74 char str[1010][30]; 75 int main() { 76 int i; 77 for( i=0; ; i++ ) { 78 if( scanf( "%s", str[i] )!=1 ) { 79 i--; 80 break; 81 } 82 T.insert( str[i] ); 83 } 84 for( int i=0; i<26; i++ ) 85 if( T.root->son[i]!=null ) 86 T.make_mark( T.root->son[i] ); 87 for( int t=0; t<=i; t++ ) 88 printf( "%s %s\n", str[t], T.get(T.stk[t]) ); 89 }