HDU1251字典樹模板
阿新 • • 發佈:2018-12-15
Problem Description Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重複的單詞出現),現在老師要他統計出以某個字串為字首的單詞數量(單詞本身也是自己的字首).
Input 輸入資料的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字串. |
http://acm.hdu.edu.cn/showproblem.php?pid=1251
#include <bits/stdc++.h> #define mset(a, x) memset(a, x, sizeof(a)) using namespace std; const int N = 400005; int cnt = 0; int tire[N][30]; string str; int sum[N]; void insert() { int rt = 0; int len = str.length(); for (int i = 0; i < len; i++) { int Index = str[i] - 'a'; if (!tire[rt][Index]) { tire[rt][Index] = cnt++; } sum[tire[rt][Index]]++; rt = tire[rt][Index]; } } int find() { int rt = 0; int len = str.length(); for (int i = 0; i < len; i++) { int Index = str[i] - 'a'; if (!tire[rt][Index]) { return 0; } rt = tire[rt][Index]; } return sum[rt]; } int main() { std::ios::sync_with_stdio(false); cnt = 1; mset(sum, 0);mset(tire, 0); while(1) { getline(cin, str); if (str.length() == 0) break; insert(); } while (cin >> str) { if (str.length() == 0) break; cout << find() << endl; } return 0; }