hihocoder #28 trie树

输入

输入的第一行为一个正整数n,表示词典的大小,其后n行,每一行一个单词(不保证是英文单词,也有可能是火星文单词哦),单词由不超过10个的小写英文字母组成,可能存在相同的单词,此时应将其视作不同的单词。接下来的一行为一个正整数m,表示小Hi询问的次数,其后m行,每一行一个字符串,该字符串由不超过10个的小写英文字母组成,表示小Hi的一个询问。
在20%的数据中n, m<=10,词典的字母表大小<=2.
在60%的数据中n, m<=1000,词典的字母表大小<=5.
在100%的数据中n, m<=100000,词典的字母表大小<=26.

输出

对于给出的每一个询问,输出一个整数Ans,表示词典中以给出的字符串为前缀的单词的个数。

样例输入
5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab
样例输出
1
0
3
0
0

代码

#include<iostream>
#include<string>
using namespace std;
 
const int Max = 26;
struct Node
{
	bool isWord{false};
	Node *child[Max]; //用边来存节点
	int L[Max];
};
 
Node * root = new Node();
 
void Insert(string word)
{
	Node *tempRoot = root;
	for (int i = 0; i < word.length(); i++)
	{
		tempRoot->L[word[i]-'a']++;
		
		if (tempRoot->child[word[i]-'a'] == NULL)
		{			
			Node *newNode = new Node();
			tempRoot->child[word[i]-'a'] = newNode;
		}
        tempRoot = tempRoot->child[word[i]-'a'];				
		
	}
	tempRoot->isWord = true; //该节点为word

}
 
int find(string word)
{
	Node *tempRoot = root;
	for (int i = 0; i < word.length(); i++)
	{
		if (tempRoot->child[word[i]-'a'] == NULL)return 0;
		else
		{			
			if (i == word.length() - 1) return tempRoot->L[word[i]-'a'];
			tempRoot = tempRoot->child[word[i]-'a'];
		}
	}
}
 
int main()
{
    int cnt{};
    string insetWords;
    cin >> cnt;
    while(cnt && (cin >>insetWords)){
        Insert(insetWords);
        cnt--;
    } 
    cin >> cnt;
    while(cnt && (cin >>insetWords)){
        cout << find(insetWords) << endl;
        cnt--;
    }
    return 0;
}

字典树,trie树是经典的问题,insert,find两个成员函数是必须的

发布了3 篇原创文章 · 获赞 0 · 访问量 31

猜你喜欢

转载自blog.csdn.net/qq_33882682/article/details/105412532