您的位置:首页 > 其它

Hdu 1671 -Phone List (字典树模板)

2017-07-20 14:32 417 查看
题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1671

题目大意:

给出n个字符串,询问是否存在某个串完全为另一个串的前缀

分析:

将字符串按长度排序后插入即可,当前字符串插入字典树时,若中途发现该结点为单词,说明该单词的前缀已被插入,返回false,若全部能顺利插入则返回true

注意:如果使用指针构造字典树,交G++可能会爆空间,建议交C++

代码:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;

typedef long long ll;

struct Trie{
Trie *next[10];
int val;
Trie(){
val = 0;
for (int i = 0 ; i < 10 ; i ++)
next[i] = NULL;
}
};

bool addword(char *str,Trie* node)
{

if (node->val!=0)
return false;
if (node->next[str[0]-'0']==NULL)
node->next[str[0]-'0'] = new Trie;
node = node->next[str[0]-'0'];
str++;
//printf("%d\t",*str);
if (*str)
return addword(str,node);
else
{
node->val++;
return true;
}
}

int query(char *str ,Trie *node)
{
// printf("%d\t",*str);
if (node->next[*str-'0']==NULL)
return 0;
else
node= node->next[*str-'0'];
++str;
if (*str)
return query(str,node);
else
return node->val;
}

void del(Trie *node)
{
for (int i = 0 ; i < 10 ; i ++)
{
if (node->next[i]!=NULL)
del(node->next[i]);
}
delete node;
node = NULL;
return;
}
struct String{
char str[20];
int len;
void read()
{
scanf("%s",str);
len = strlen(str);
}
bool operator <(const String& a)
{
return len<a.len;
}
}s[12000];

int main()
{
int T,n;
//printf("hello\n");
Trie *head;
//printf("world\n");
scanf("%d",&T);

while (T--)
{

scanf("%d",&n);
head = new Trie;
for (int i = 1;  i <= n ; i ++)
{
s[i].read();
}
sort(s+1,s+n+1);
int f = 1;
//printf("ok\n");
for (int i = 1 ; i <= n ; i ++)
{
if (!addword(s[i].str,head))
{
f = 0;
break;
}
}
//printf("fuck\n");
if (!f)
printf("NO\n");
else
printf("YES\n");
del(head);

}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: