您的位置:首页 > 其它

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

2015-11-08 14:32 288 查看
题目链接: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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  字典树 释放内存