统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 17106 Accepted Submission(s): 7370
Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana band bee absolute acm ba b band abc
Sample Output
2 3 1 0
Author
Ignatius.L
Recommend
Ignatius.L
思路:
Trie 每个节点保存一下以当前节点为前缀的单词数即可
因为数组开小了 WALE好久
#include <stdio.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <queue>
#include <set>
using namespace std;
//#define WIN
#ifdef WIN
typedef __int64 LL;
#define iform "%I64d"
#define oform "%I64d\n"
#define oform1 "%I64d"
#else
typedef long long LL;
#define iform "%lld"
#define oform "%lld\n"
#define oform1 "%lld"
#endif
#define S64I(a) scanf(iform, &(a))
#define P64I(a) printf(oform, (a))
#define S64I1(a) scanf(iform1, &(a))
#define P64I1(a) printf(oform1, (a))
#define FOR(i, s, t) for(int (i)=(s); (i)<(t); (i)++)
const int INF = 0x3f3f3f3f;
const double eps = 10e-9;
const double PI = (4.0*atan(1.0));
const int maxsize = 1000000;
struct Trie {
int size;
int val[maxsize];
int sum[maxsize];
int ch[maxsize][26];
Trie() {
size = 1;
memset(sum, 0, sizeof(sum));
memset(ch[0], 0, sizeof(ch[0]));
}
int idx(char c) {
return c - 'a';
}
void insert(char * s, int v) {
int len = strlen(s);
int u = 0;
for(int i=0; i<len; i++) {
int c = idx(s[i]);
if(!ch[u][c]) {
memset(ch[size], 0, sizeof(ch[size]));
val[size] = 0;
ch[u][c] = size++;
}
u = ch[u][c];
sum[u]++;
}
val[u] = v;
}
int query(char * s) {
int len = strlen(s);
int u = 0;
for(int i=0; i<len; i++) {
int c = idx(s[i]);
u = ch[u][c];
if(!u) return 0;
}
int ret = sum[u];
return ret;
}
};
char s[20];
Trie trie;
int main() {
while(1) {
gets(s);
if(strlen(s) == 0) break;
trie.insert(s, 1);
}
while(scanf("%s", s) != EOF) {
int ans = trie.query(s);
printf("%d\n", ans);
}
return 0;
}