LeeBlog

导航

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

posted on 2011-03-15 22:22  LeeBlog  阅读(183)  评论(0编辑  收藏  举报