统计难题
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)Total Submission(s): 35573 Accepted Submission(s): 13301
注意:本题只有一组测试数据,处理到文件结束.
banana band bee absolute acm ba b band abc
2 3 1 0
字典树模板题,每个结点设一个值sum,表示以它为前缀的字符串的个数。在插入字符串时,每经过一个结点,将该结点的sum值增加1即可。
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
struct Trie
{
Trie* next[26];
int sum;
Trie() : sum(0) {
for(int i = 0; i < 26; i++) next[i] = NULL;
}
};
Trie* root;
void Insert(char* s)
{
Trie* rt = root;
int len = strlen(s);
for(int i = 0; i < len; i++) {
int k = s[i] - 'a';
if (rt -> next[k] == NULL) rt -> next[k] = new Trie();
rt = rt -> next[k];
rt -> sum++;
}
}
int Query(char* s)
{
Trie* rt = root;
int len = strlen(s);
for(int i = 0; i < len; i++) {
int k = s[i] - 'a';
if (rt -> next[k] == NULL) return 0;
rt = rt -> next[k];
}
return rt -> sum;
}
int main()
{
char s[10];
root = new Trie();
while(gets(s)) {
if(s[0] == 0) break;
Insert(s);
}
while(gets(s)) {
if(s[0] == 0) break;
printf("%d\n",Query(s));
}
}
207


&spm=1001.2101.3001.11974&articleId=52988494&d=1&t=3&u=2f98588a0a884482bb2b1caf9ec97dc0)

被折叠的 条评论
为什么被折叠?



