Trie树
https://hihocoder.com/problemset/problem/1014
代码
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct TrieTree
{
vector<TrieTree*> subtrees;
int L;
char var;
TrieTree(int L_, char var_)
{
L = L_;
var = var_;
}
};
int main()
{
int N;
TrieTree *Tree = new TrieTree(0, '+');
string str;
cin >> N;
// 建Trie树
for (int i = 0; i < N; i++)
{
// 输入要插入的字符串
cin >> str;
TrieTree *p = Tree;
for (auto c : str)
{
if (p->subtrees.size() == 0)
{
TrieTree *tmpNode = new TrieTree(1, c);
p->subtrees.push_back(tmpNode);
p = tmpNode;
}
else
{
bool flag = false;
for (auto subtree : p->subtrees)
{
if (subtree->var == c)
{
subtree->L++;
p = subtree;
flag = true;
break;
}
}
if (flag == false)
{
TrieTree *tmpNode = new TrieTree(1, c);
p->subtrees.push_back(tmpNode);
p = tmpNode;
}
}
}
}
cin >> N;
// 查询
for (int i = 0; i < N; i++)
{
cin >> str;
TrieTree *p = Tree;
bool zeroflag = false;
for (auto c : str)
{
if (p->subtrees.size() == 0)
{
zeroflag = true;
break;
}
else
{
bool flag = false;
for (auto subtree : p->subtrees)
{
if (subtree->var == c)
{
p = subtree;
flag = true;
break;
}
}
if (flag == false)
{
zeroflag = true;
break;
}
}
}
if (zeroflag == true)
printf("0\n");
else
printf("%d\n", p->L);
}
return 0;
}