题意:给你n个电话号码,判断是否存在一个电话号码是另一个号码的前缀,如果存在则输出no,否则输出yes
#include<stdio.h>
#include<string.h>
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int ct;
struct TireNode
{
int count;
struct TireNode *branch[10];
TireNode()
{
count = 0;
for (int i = 0; i < 10; i++)
branch[i] = NULL;
}
}NodeNum[100000];//静态数组储存Tire树结点!
//Tire树的插入操作!
void TireInsert(TireNode *&root, string str)
{
int i, len;
len = str.length();
TireNode *p = root;
for (i = 0; i < len; i++){
if (!p->branch[str[i]-'0']){
p->branch[str[i]-'0'] = &NodeNum[ct];
ct++;
}
p = p->branch[str[i]-'0'];
p->count++;
}
return ;
}
//Tire树的查询操作!
bool TireSearch(TireNode *root, string str)
{
if (root == NULL)
return 0;
int i, len;
len = str.length();
TireNode *p = root;
for (i = 0; i < len; i++){
p = p->branch[str[i]-'0'];
if (p->count == 1)
return 1;
}
return 0;
}
int main()
{
int tc, i, n;
string phone[10010];
bool flag;
cin >> tc;
while (tc--){
cin >> n;
flag = true;
memset(NodeNum, NULL, sizeof(NodeNum));
TireNode *root = &NodeNum[0];
ct = 1;
for (i = 0; i < n; i++){
cin >> phone[i];
TireInsert(root, phone[i]);
}
sort(phone, phone+n);
for (i = 0; i < n; i++){
if (!TireSearch(root, phone[i])){
flag = false;
break;
}
}
if (flag)
cout << "YES" << endl;
else
cout << "NO" << endl;
}
system("pause");
}