题目大意:
给你一连串的电话号码,确定没有一个电话号码是另一个电话号码的前缀:
字典树的题,没什么好说的,可以用来练手;
这道题需要注意的是回收空间;
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
using namespace std;
struct Node{
int cnt;
Node *next[10];
Node(){
cnt = 0;
for(int i = 0; i < 10; ++i)
next[i] = nullptr;
}
};
string s[10010];
Node *root;
void remove_tree(Node *u){
if(u == nullptr) return ;
for(int i = 0; i < 10; ++i)
remove_tree(u->next[i]);
delete u;
}
int main()
{
int T, n;
scanf("%d", &T);
while(T--){
int ok = 1;
root = new Node;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
cin >> s[i];
Node *p = root;
for(unsigned j = 0; j < s[i].size(); ++j){
int t = s[i][j] - '0';
if(p->next[t] == nullptr)
p->next[t] = new Node;
p = p->next[t];
p->cnt++;
}
}
for(int i = 0; i < n; ++i){
Node *p = root;
for(unsigned j = 0; j < s[i].size(); ++j){
int t = s[i][j]-'0';
p = p->next[t];
}
if(p->cnt > 1){
ok = 0;
break;
}
}
if(ok)
printf("YES\n");
else
printf("NO\n");
remove_tree(root);
//回收空间的时候我多加了一句delete root,然后找了两天的bug;
}
return 0;
}