1. 程式人生 > >Trie樹_CH1601_字首統計

Trie樹_CH1601_字首統計

點此開啟題目頁面

思路分析:

    直接應用Trie樹即可, 下面給出AC程式碼:

//CH1601_字首統計
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAX = 1e6 + 5;
int trie[MAX][26], nex[MAX], tot, cnt[MAX];//cnt[i]:trie[i]對應字串結尾個數 
char s[MAX];
int main(){
	int N, M; scanf("%d %d", &N, &M);
	for(int i = 1; i <= N; ++i){
		int len = (scanf("%s", s + 1), strlen(s + 1)), k = 0;
		for(int i = 1; i <= len; k = trie[k][s[i] - 'a'], ++i)
			if(!trie[k][s[i] - 'a']) trie[k][s[i] - 'a'] = ++tot;
		++cnt[k];
	}
	for(int i = 1; i <= M; ++i){
		int len = (scanf("%s", s + 1), strlen(s + 1)), res = 0, k = 0;
		for(int i = 1; i <= len; ++i){
			if(!(k = trie[k][s[i] - 'a'])) break;	
			res += cnt[k];	
		} 
		cout << res << endl;
	}
	return 0;
}