您的位置:首页 > 其它

hihocode 1014 Trie树

2016-04-22 22:16 513 查看
前些日子清明节。。 无聊,自学了字典树的皮毛

首先是仓鼠学长在上学期给了我一个500多行的字典树代码。。

然后似乎是队长大人调侃说我可以在70行里面完成。。

这个梗一直记着。。 500多行的代码倒是丢了。。

于是就稍微看了一下最基础的。。

感觉这种方式空间占用好大。。

下面给出模板,我太懒把test写成全局了。。 指针只要稍微改一下就好了。。

唔。。明天省赛,和江一起打镜像,我要好好表现啦!

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
string test;
struct trie
{
trie *next[26];
int v;
trie()
{
v=0;
for(int i=0;i<26;i++)
{
next[i]=NULL;
}
}
};
trie root;
void build()
{
int len=test.length();
trie *p=&root;
for(int i=0;i<len;i++)
{
int id=test[i]-'a';
if(p->next[id]==NULL)
{
trie *q=new trie;
p->next[id]=q;
}
p=p->next[id];
p->v++;
}
}
int find()
{
int len=test.length();
trie *p=&root;
for(int i=0;i<len;i++)
{
int id=test[i]-'a';
if(p->next[id]==NULL)
{
return 0;
}
p=p->next[id];
}
return p->v;
}
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
test.clear();
cin>>test;
build();
}
int m;
cin>>m;
for(int i=1;i<=m;i++)
{
test.clear();
cin>>test;
int ans=find();
cout<<ans<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模板 字典树