字典树模板
HDU 1251
AC代码
#include<cstdio> #include<cstdlib> #include<cstring> #include<string.h> #include<cmath> #include<algorithm> #include<queue> #include<stack> #include<deque> #include<iostream> using namespace std; typedef long long LL; const int MOD = 1000000007; const int maxn = 2e6 + 5; int tree[maxn][30]; int sum[maxn]; int tot; char ss[maxn]; void insert(char* str) { int len = strlen(str); int root = 0; for(int i = 0; i < len; i++) { int id = str[i] - 'a'; if(!tree[root][id]) tree[root][id] = ++tot; sum[ tree[root][id] ] ++; root = tree[root][id]; } } int find(char* str) { int len = strlen(str); int root = 0; for(int i = 0; i < len; i++) { int id = str[i] - 'a'; if(tree[root][id]) { root = tree[root][id]; } else { return 0; } } return sum[root]; } int main() { tot = 0; while(gets(ss)) { if(ss[0] == '\0') break; insert(ss); } while(scanf("%s", ss) != EOF ) { int ans = find(ss); printf("%d\n", ans); } return 0; }