1471 phone list
很显然,这是一个trie的模板题,可惜,我一点思路都没有
算是很模板的题目了
就是在建树的时候需要进行一个小小的常识,这些小常识我们必须在纸上推出来
如果我们发现当前的节点没有,需要在 trie上重新建一个点的话,那么肯定没有
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
const int SIZE=1e5+5;
int t;
int tree[SIZE][26];//第一维节点个数,第二个是深度
int tail[SIZE];//树的某个节点结尾的串并且是已知串的数量
string s;
int cnt;
int f,flag;
int n;
int insert()
{
int len=s.size();
int now=0;
for(int i=0;i<len;i++)
{
int x=s[i]-'0';//获取节点
if(tree[now][x]==0)//不存在节点
{
tree[now][x]=++cnt;//插入节点
f=1;//新建的点不存在前缀
}
now=tree[now][x];
if(tail[now])
flag=1;
}
tail[now]=1;
return flag==1||f==0;
}
int main()
{
cin>>t;
while(t--)
{
memset(tree,0,sizeof(tree));
memset(tail,0,sizeof(tail));
cnt=0;
int res=0;
cin>>n;
while(n--)
{
flag=f=0;
cin>>s;
if(insert())
res=1;
}
printf("%s\n",res==1?"NO":"YES");
}
return 0;
}
使用Trie数据结构解决字符串集合问题
这篇博客探讨了一道关于Trie树的编程题目,作者分享了如何利用Trie树来处理字符串集合的问题。在建树过程中,强调了需要考虑节点不存在时的处理,以及如何判断字符串是否为已知串。代码中展示了C++实现,通过插入字符串并检查是否存在前缀来解决问题。
244

被折叠的 条评论
为什么被折叠?



