统计难题

来源:互联网 发布:战旗tv直播软件 编辑:程序博客网 时间:2024/05/05 17:48

统计难题

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 37320    Accepted Submission(s): 13799


Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
 

Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.

注意:本题只有一组测试数据,处理到文件结束.
 

Output
对于每个提问,给出以该字符串为前缀的单词的数量.
 

Sample Input
bananabandbeeabsoluteacmbabbandabc
 

Sample Output
2310



解题报告:字典树模板题,注意提交时用C++编译器,G++会超时。


code:

#include<iostream>#include<stdio.h>#include<queue>#include<vector>#include<stack>#include<cstring>#include<algorithm>using namespace std;typedef long long ll;const int maxn=100005;const int MAX=26;typedef struct node{    struct node *next[MAX];    int flag;  //该字母出现的次数}Trie;Trie *root;/*root要初始化root=(Trie *)malloc(sizeof(Trie));root->flag=0;for(int i=0;i<MAX;i++){    root->next[i]=NULL;}*/void createTrie(char *str) //创建一棵字典树{    int len = strlen(str);    Trie *p = root, *q;    for(int i=0; i<len; i++)    {        int id = str[i]-'a'; //小写字母        if(p->next[id] == NULL)        {            q = (Trie *)malloc(sizeof(Trie));            q->flag = 0;            for(int j=0; j<MAX; j++)                q->next[j] = NULL;            p->next[id] = q;        }        p = p->next[id];        p->flag++;    }}int findTrie(char *str) //找出以str字符串为前缀的单词的数量.{    int len = strlen(str);    Trie *p = root;    for(int i=0; i<len; i++)    {        int id = str[i]-'a';        p = p->next[id];        if(p == NULL)   //若为空集,表示不存以此为前缀的串            return 0;    }    return p->flag;}int main(){  //  freopen("input.txt","r",stdin);    root=(Trie *)malloc(sizeof(Trie)); //初始化    root->flag=0;    for(int i=0;i<MAX;i++){        root->next[i]=NULL;    }    char s[15];    while(gets(s)){        if(strlen(s)==0)            break;        createTrie(s);    }    while(~scanf("%s",s)){        printf("%d\n",findTrie(s));    }    return 0;}

1 0
原创粉丝点击