题意:给出n个数字串,问其中是否有一个串是另一个串的前缀。(静态建树的模板)
思路:基础的Trie。必须使用静态建树,否则会超时。还有就是有可能是前面的串是后面的串的前缀,也有可能后面的串是前面的串的前缀,如:
2
2
1
12
2
12
1
代码如下:
#include<iostream>
using namespace std;
const int Max = 100000;
const int branchNum = 10;
struct tree_node
{
bool isstr;
tree_node *next[branchNum];
}root, node[Max];
int p;
bool flag;
void insert(char *word)
{
bool new_flag = false;
tree_node *location = &root;
while(*word)
{
if(location->isstr == true)
{ // 前面的串为word的前缀。
flag = false;
return;
}
if(location->next[*word-'0']==NULL)
{
new_flag = true; // 有新的节点开辟,证明word不为前面的串的前缀。
node[p].isstr = false; // 新节点的初始化。
memset(node[p].next, NULL, sizeof(node[p].next));
location->next[*word-'0'] = &node[p ++];
}
location = location->next[*word-'0'];
word++;
}
location->isstr = true;
if(!new_flag)
flag = false; // word为前面的串的前缀。
}
int main()
{
int t, n;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
p = 0;
flag = true;
memset(root.next, NULL, sizeof(root.next)); // 记得每次都得做root的初始化,WA在这。
while(n--)
{
char word[11];
scanf("%s", word);
if(flag)
insert(word);
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}