HDOJ.1251

今天我学习了字典树(trie tree)#

作者:xxy
出处:
http://www.cnblogs.com/TheRoadToTheGold/

学的

可以用来查询字符串是多少字符串的前缀

sum在插入时每一层都会加1 感觉非常精妙


#include<bits/stdc++.h>

using namespace std;

int trie[400001][26],len,root,tot,sum[400001];
bool p;
int n,m;
char s[11];

void insert()
{
	len = strlen(s);
	root = 0;
	for(int i=0;i<len;++i)
	{
		int id = s[i]-'a';
		if(!trie[root][id])	trie[root][id] = ++tot;
		sum[trie[root][id]]++;
		root = trie[root][id];
	}
}

int search()
{
	root = 0;
	len = strlen(s);
	for(int i=0;i<len;++i)
	{
		int id = s[i]-'a';
		if(!trie[root][id])	return 0;
		root = trie[root][id];
	}
	return sum[root];
}
int main()
{
	while(1)
	{
		cin.getline(s,11);
		if(s[0]>'z' ||s[0]<'a')	break;
		insert();
		//getchar();
	}
	while(cin>>s)
	{
		if(!s[0])	break;	//cin >> s;
		cout <<search()<<endl;
	}
	return 0;
}

如果只是查询单词是否存在 可以直接用map

原文地址:https://www.cnblogs.com/xxrlz/p/10380878.html