2 3 911 97625999 91125426 5 113 12340 123440 12345 98346
NO YES
#include <cstdio>
#include <cstring>
char s[15];
bool flag;
struct node
{
node *next[10];
bool end;
node()
{
memset(next, false, sizeof(next));
end = false;
}
};
void Insert(node *p, char *s)
{
bool f = true;
for(int i = 0; s[i] != '\0'; i++)
{
int idx = s[i] - '0';
if(p -> next[idx] == NULL)
{
p -> next[idx] = new node();
f = false;
}
p = p -> next[idx];
}
p -> end = true;
if(f)
flag = true;
}
void Search(node *p, char *s)
{
for(int i = 0; s[i] != '\0'; i++)
{
int idx = s[i] - '0';
if(p -> end)
{
flag = true;
return;
}
if(p -> next[idx] != NULL)
p = p -> next[idx];
}
}
void Delete(node *p)
{
for(int i = 0; i < 10; i++)
if(p -> next[i])
Delete(p -> next[i]);
delete p;
}
int main()
{
int T, n;
scanf("%d", &T);
while(T--)
{
flag = false;
node *root = new node();
scanf("%d", &n);
for(int i = 0; i < n; i++)
{
scanf("%s", s);
Insert(root, s);
if(!flag)
Search(root, s);
}
printf("%s\n", flag ? "NO" : "YES");
Delete(root);
}
}HDU 1671 Phone List (Trie树 好题)
原文地址:http://blog.csdn.net/tc_to_top/article/details/43918461