HDU 1075 What are you talking about(trie树)

   感动天感动地啊!这道题我提交了整整11次!Runtime Error(ACCESS_VIOLATION)。错的地方在代码里写吧。。主要还是trie树的各种方法没写熟。

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MAXNUM 27
typedef struct tnode
{
    int mark,count;
    tnode *next[MAXNUM];
    char words[20];
    
}tnode;
tnode *root;
char result[20];
void init()
{
    int i;
    root=(tnode*)malloc(sizeof(tnode));
    for(i=0;i<MAXNUM;i++)
        root->next[i]=NULL;
  root->mark=0;

}
void  insert(char words[20],char *str)
{
    tnode *r=root,*child;
    int i,flag=0;
    while(*str!='\0')
    {
        if(r->next[*str-'a']==NULL)
        {   flag=1;
            child=(tnode*)malloc(sizeof(tnode));
            for(i=0;i<MAXNUM;i++)
                child->next[i]=NULL;
            child->mark=0;
            child->count=0;
            r->next[*str-'a']=child;


        }
        r->next[*str-'a']->count++;
        r=r->next[*str-'a'];
        str++;

    }

    r->mark=1;
    strcpy(r->words,words);

}

void search(char *s)
{
    tnode *r=root;
    int i,len;
    len=strlen(s);
    i=0;
//就是这个地方,我之前写的是while(r->next[*str-'a']!=NULL),理所当然的RE了
    for(i=0;i<len;i++)
    {
        if(r->next[*s-'a']==NULL)return;
        if(i==len-1&&(r->next[*s-'a']->mark==1))  {strcpy(result,r->next[*s-'a']->words);return;}
       r=r->next[*s-'a'];
        s++;
       
    
   }
    return;
}

int main()
{
    char str[3100],words[20],temp[3100];
    int i,j,flag,len;
    init();
    scanf("START");
    while(strcmp(str,"END")!=0)
    {
        
        scanf("%s",words);
        if(strcmp(words,"END")==0)break;
        scanf("%s",str);
        insert(words,str);    
          
    }
    gets(str);
    scanf("START");
    gets(str);
  gets(temp);
    while((strcmp(temp,"END")!=0))
    {
             
            
              i=0;
              len=strlen(temp);
              while(i<len)
              {
                  j=0;
                  flag=0;
                  while((temp[i]>='a'&&temp[i]<='z'))

                  {
                      flag=1;
                      str[j++]=temp[i++];

                  }
                 if(flag) 
                 {
                     str[j]='\0';
                     result[0]='\0';
                     search(str);
                  if(result[0]=='\0')
                      printf("%s",str);
                 else  printf("%s",result);
                 }
                  printf("%c",temp[i]);
                  i++;
              }
              printf("\n");
              gets(temp);

    }

  return 0;
}
原文地址:https://www.cnblogs.com/leeshum/p/3029517.html