字典樹-統計難題-板子題-詳解

Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字符串爲前綴的單詞數量(單詞本身也是自己的前綴). 

Input

輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串. 

注意:本題只有一組測試數據,處理到文件結束. 

Output

對於每個提問,給出以該字符串爲前綴的單詞的數量. 

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<set>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn = 1e5+5;
const int N = 1e6;
int trie[N][30],num[N];
int root  = 0,index = 1;
void insert(char * data)
{
	int len = strlen(data);//先獲取字符要創建的字符常熟
	int rt = root;//首先獲取一個根初始爲0
	for(int i = 0;i < len ;i++)//遍歷
	{
		int y = data[i] - 'a';//轉數字存數組
		if(trie[rt][y] == 0)
		{
			trie[rt][y] = index++;//如果字符和以前的沒重複前綴將會進去
		}
		rt = trie[rt][y];//重複也會向下遍歷再找沒重複的
		num[rt]++;//標記該點便利過幾次即到這裏的字符串有幾次相同的字串
	}
}//建立字典樹
int query(char* str)
{
	int len = strlen(str);//查詢長度
	int rt = root;//初始化根
	for(int i = 0;i < len;++i)//遍歷字符串
	{
		int y = str[i]-'a';//轉數字
		rt = trie[rt][y];//向下便利
		if(rt == 0)
		{
			return 0;
		}//如果沒找到輸出0返回
	}
	return num[rt];//找到輸出到找完的字串存的有幾次相同字串
}//在樹上找
int main()
{
	char s1[maxn];
	char s2[maxn];
	while(gets(s1))
	{
		if(strcmp(s1,"")==0) break;
		insert(s1);
	}//獲取主串建樹
	while(cin>>s2)
	{
		printf("%d\n",query(s2));
	}//輸出查詢後的幾次相同字串
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章