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;
}