题目链接: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;
}