题目链接:http://hihocoder.com/problemset/problem/1014
题目大意,给出了若干个串为字典,然后询问若干个串,问字典中有多少串是以这些串为开头的(前缀)
#include <iostream> #include <string> #include <cstring> using namespace std; #define MAX_N 1000100 #define MAX_C 26 struct Trie { int *ch[MAX_N]; int tot; int cnt[MAX_N]; Trie() { tot = 0; memset( ch, 0, sizeof(ch) ); memset( cnt, 0, sizeof(cnt) ); } void insert( const string s ) { int p = 0; for ( int i = 0, len=s.size() ; i < len ; ++ i ) { if ( ch[p] == NULL ) { ch[p] = new int[MAX_C]; memset( ch[p], -1, sizeof(int)*MAX_C ); } if ( ch[p][s[i]-'a'] == -1 ) { ch[p][s[i]-'a'] = ++tot; } p = ch[p][s[i]-'a']; cnt[p] ++;// 经过结点p的值+1 } } int find( const string s ) { int p = 0; for ( int i = 0 , len = s.size() ; i < len ; ++ i ) { if ( ch[p] == NULL ) return 0; if ( ch[p][s[i]-'a'] == -1 ) { return 0; } p = ch[p][s[i]-'a']; } return cnt[p];// 返回结点p的值 } }; Trie trie; int main() { string s; int n; cin >> n; for ( int i = 0 ; i < n ; ++ i ) { cin >> s; trie.insert(s); } cin >> n; for ( int i = 0 ; i < n ; ++ i ) { cin >> s; cout << trie.find(s) << endl; } return 0; }