题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1075
Trie树的入门题。
推荐入门博客 : https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html
入门题 懂了基本的这道题就可以过了,就是唯一不一样的是G++超了内存,C++不爆。
代码:
#include<iostream>
#include<string>
using namespace std;
struct node{
int Count;//统计单词前缀出现次数
node *next[26];//叶子指针
int flag;//标记是否构成单词
node():Count(0),flag(0){//初始化
for(int i = 0;i < 26;i++)
next[i] = NULL;
}
};
void insert(node *root,string &s)
{
node *temp = root;
int len = s.length();
for(int i = 0;i < len;i++)
{
int id = s[i] - 'a';
if(temp->next[id] == NULL)
temp->next[id] = new node();
temp = temp->next[id];
temp->Count = temp->Count+1;//标记前缀数量
}
temp->flag = 1;//单词结束 完整单词
}
int find(node *root,string &s)
{
node *temp = root;
int len = s.length();
for(int i = 0;i < len;i++)
{
int id = s[i] - 'a';
if(temp->next[id] != NULL)
temp = temp->next[id];
else
return 0;
}
return temp->Count;
}
int main()
{
node *root = new node();
string s;
int flag=0;
while(getline(cin,s))
{
if(flag)//开始查询
printf("%d\n",find(root,s));
else
{
if(!s.empty())//非空
insert(root,s);
else//后边输入的为查询
flag=1;
}
}
return 0;
}