【字典树】HDU1671Phone List(论释放内存的重要性)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1671

一道简单的模板题,但是这个题目是多组数据。所以如果你不释放内存,很有可能你就会MLE到死。。。orz....

增加一个释放内存的函数就可以轻松搞定了。不过最好还是能够养成这样一个习惯,那就是在使用数据结构的指针是,每次都能够释放。

#include<iostream>
#include<string>
#include<cstdio>
#include<cstring>
#include<stdlib.h>
using namespace std;
const int N=10;
char s[10002][11];
struct node{
    bool flag;
    node *next[N];
    node(){
        flag=false;
        memset(next,0,sizeof(next));
    }
};
node *p,*head=new node();
void Insert(char s[])
{
    p=head;
    int i=0;
    while(s[i]){
        int id=s[i++]-'0';
        if(p->next[id]==NULL) p->next[id]=new node();
        p=p->next[id];
    }
    p->flag=true;
}
bool Query(char s[])
{
    p=head;
    int i=0;
    while(s[i]){
        int id=s[i++]-'0';
        if(p->next[id]==NULL) return false;
        if(p->flag) return true;
        p=p->next[id];
    }
    return false;
}
int deal(node* T)       //  释放内存空间,尤为重要。
{
    int i;
    for(i=0;i<=9;i++)
    {
        if(T->next[i]!=NULL)
            deal(T->next[i]);
    }
    free(T);            //  头文件 "stdlib.h"
    return 0;
}
int main()
{
    int t,n,i;
    cin>>t;
    while(t--){
        cin>>n;
        head=new node();
        for(i=0;i<n;i++){
            cin>>s[i];
            Insert(s[i]);
        }
        for(i=0;i<n;i++){
            if(Query(s[i])){
                printf("NO\n");
                break;
            }
        }
        if(i==n) printf("YES\n");
        deal(head);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值