HDU 1671 Phone List
这题是字典树的以简单题但我开始一直不能水过,后来才发现rt用的不是自定义,再循环使用时没有初始化,后来将结构体自定义,果断水过,表示以后所有的结构体都用自定义
#include<stdio.h> #include<stdlib.h> #include<string.h> const int max = 10; typedef struct T { T *ch[max]; int f; }Trie; int flag = 1; char in[50]; void init( T *t ) { t -> f = 0; for( int i = 0; i < max; ++i ) t -> ch[i] = NULL; } void insert( T *t,char *in ) { if( !flag ) return ; if( *in ) { if( t -> f )//若已存在此前缀 { flag = 0; } if( t -> ch[*in - '0'] == NULL ) { t -> ch[*in -'0'] = ( T * )malloc( sizeof( T ) ); init( t -> ch[*in - '0'] ); } insert( t -> ch[*in - '0'],in + 1 ); } else { t -> f = 1; for( int i = 0 ; i < max; ++i )//若此字符串是其他字符串的前缀 if( t -> ch[ i ] != NULL ) {flag = 0;} } } int Free( T *t ) { if( t == NULL ) return 0; for( int i = 0; i < max ; ++i ) if( t -> ch[i] != NULL ) Free( t -> ch[i] ); free( t ); return 0; } int main( ) { int t,n; scanf( "%d",&t ); while( t-- ) { Trie *rt; rt = ( T * )malloc( sizeof( T ) );//一直WA所在地 init( rt ); scanf( "%d",&n ); flag = 1; while( n-- ) { scanf( "%s",in ); insert( rt,in ); } flag ? printf( "YES\n" ) : printf( "NO\n" ); Free( rt ); } return 0; }
本人还是新手 ,转载请注明来自Lvsi‘s home