HDU1251 統計難題(字典樹)
阿新 • • 發佈:2018-08-11
lag != tac NPU math def tput struct bee
HDU1251 統計難題
Ignatius最近遇到一個難題,老師交給他很多單詞(只有小寫字母組成,不會有重復的單詞出現),現在老師要他統計出以某個字符串為前綴的單詞數量(單詞本身也是自己的前綴).
Input
輸入數據的第一部分是一張單詞表,每行一個單詞,單詞的長度不超過10,它們代表的是老師交給Ignatius統計的單詞,一個空行代表單詞表的結束.第二部分是一連串的提問,每行一個提問,每個提問都是一個字符串.
註意:本題只有一組測試數據,處理到文件結束.
Output
對於每個提問,給出以該字符串為前綴的單詞的數量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2
3
1
0
題解
題意
中文題面。統計以該單詞為前綴的字符串數量。
思路
建立字典樹,在建樹過程中,對於經過的節點,增加數值。當查找時返回該數值即可。
代碼
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; typedef long long ll; const double PI = acos(-1.0); const double eps = 1e-6; const int INF = 0x3f3f3f3f; #define REP(i,n) for(int i=0;i<(n);i++) const int SIZE = 26; const int MAXN = 1e6+10; struct Tire{ int sz; int ch[MAXN][SIZE]; int val[MAXN]; Tire(){ sz = 1; memset(ch[0],0,sizeof(ch[0])); memset(val,0,sizeof(val)); } int idx(char c){ return c-'a'; } void insert(char *s, int v){ int u = 0,n = strlen(s); for(int i=0;i<n;i++){ int c = idx(s[i]); if(!ch[u][c]){ memset(ch[sz],0,sizeof(ch[sz])); val[sz] = 0; ch[u][c] = sz++; } u = ch[u][c]; val[u]=val[u]+1; } } int query(char *s){ int u =0,n = strlen(s); for(int i=0;i<n;i++){ int c = idx(s[i]); if(!ch[u][c]){ return -1; } u = ch[u][c]; } return val[u]; } }Tree; int main(){ char str[15]; while(gets(str)&&str[0]!='\0'){ Tree.insert(str,1); } while(scanf("%s",str)!=EOF){ int flag = Tree.query(str); if(flag==-1) printf("%d\n",0); else printf("%d\n",flag); } return 0; }
HDU1251 統計難題(字典樹)