Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台

字典树 week3EX第一题 注意释放内存 hdu1671 2012-4-16

汗,字典树,采用动态内存开辟空间后要注意释放内存,这样就不会造成Memory Limit Exceeded,没释放结果wa了5次,悲剧~~,在平时设置链表等开辟动态内存存储空间中也要注意这种情况,尤其是要注意树空间的释放。

正确代码~~

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void maketire(char temp1[]);
int  search(char temp2[]);


structnode{
       structnode *next[27];
       int count;
       }*root;
int freedom(structnode *p);
       
int main()
{   char temp[10020][12];
    int sum=0,i,n,m,len,judge;

    scanf("%d",&n);
    while(n--){
          root=(structnode*)malloc(sizeof(structnode));
            for( i=0;i<10;i++)
            root->next[i]=NULL;
            root->count=0;         
       scanf("%d",&len);
       for(i=0;i<len;i++)
       {
        scanf("%s",temp[i]);                 
        maketire(temp[i]);     
       }          
       judge=0;                         
    for( i=0;i<len;i++){
            
           judge=search(temp[i]);
           if(judge==1)break;            
                       }
        if(judge==1)printf("NO\n");
        else printf("YES\n");    
        
        freedom(root);
        }    
    return 0;
  }

void maketire(char temp1[]) {
     structnode *r,*tem;
     int len,i,j;
     r=root;
     
     len=strlen(temp1);
     for(i=0;i<len;i++){
         if(r->next[temp1[i]-'0']==NULL){
                tem=(structnode*)malloc(sizeof(structnode));
                   for(j=0;j<10;j++)
                   tem->next[j]=NULL;
                tem->count=0;
                r->next[temp1[i]-'0']=tem;
                                       }                         
              r=r->next[temp1[i]-'0'];
              r->count++;
                            
                       }
     }

int  search(char temp2[]){
     structnode *r;
     int len,i;
     r=root;
     len=strlen(temp2);
     for(i=0;i<len;i++){
         if(r->next[temp2[i]-'0']!=NULL){
               
               r=r->next[temp2[i]-'0'];                
               if((i==len-1)&&(r->count>1))return 1;  
                    if(r->count==1)break;                          
                                         }                  
                        }  
              return 0;           
     }
     
     
     
int freedom(structnode *p){                                  /*   这里就是树空间的释放代码~~重要~~ */
    int i=0;
    for(i=0;i<10;i++)
    if(p->next[i]!=NULL) freedom(p->next[i]);
    free(p);
    
    }     
     

 

posted @ 2012-04-16 21:55  大嘴鸟  阅读(325)  评论(0编辑  收藏  举报
Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台