链接:
https://vjudge.net/problem/HDU-1251
题意:
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
思路:
直接考虑字典数, 每个节点记录经过的次数,次数就是前缀数目.
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <vector> //#include <memory.h> #include <queue> #include <set> #include <map> #include <algorithm> #include <math.h> #include <stack> #include <string> #include <assert.h> #include <iomanip> #define MINF 0x3f3f3f3f using namespace std; typedef long long LL; const int INF = 1e9; const int MAXN = 1e6+10; int cnt, n; char word[100]; struct Node { int Ends; int Pass; int Next[30]; void Init() { Ends = 0; Pass = 0; memset(Next, 0, sizeof(Next)); } }Trie[MAXN]; void Insert(char* val) { int root = 0; int len = strlen(val); for (int i = 0;i < len;i++) { if (Trie[root].Next[val[i]-'a'] == 0) { Trie[root].Next[val[i]-'a'] = ++cnt; Trie[cnt].Init(); } root = Trie[root].Next[val[i]-'a']; Trie[root].Pass++; } Trie[root].Ends++; } int Query(char *val) { int root = 0; int len = strlen(val); for (int i = 0;i < len;i++) { if (Trie[root].Next[val[i]-'a'] == 0) return 0; root = Trie[root].Next[val[i]-'a']; } return Trie[root].Pass; } int main() { while (gets(word)) { if (word[0] == '\0') break; Insert(word); } while (~scanf("%s", word)) { printf("%d\n", Query(word)); } return 0; }