NYOJ685 查找字符串(字典树)

来源:互联网 发布:软件研发队伍介绍 编辑:程序博客网 时间:2024/06/03 17:24

查找字符串
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
小明得到了一张写有奇怪字符串的纸,他想知道一些字符串出现了多少次,但这些字符串太多了,他想找你帮忙,你能帮他吗?输入字符包括所有小写字母、‘@’、‘+’。
输入
第一行包含一个整数T(T<=100).表示测试数据组数。
接下来每组数据第一行包含两个整数n,m(n,m<100000),分别表示有n个字符串,小明要问你m次。
接下来n行,每行包含一个字符串,长度不大于15。
接下来m行,每行包含一个字符串,表示小明要问该串出现的次数。
输出
输出每组小明询问数串出现的次数。
样例输入
1
5 3
hello
it@is+so@easy
hello
ibelieveicanac
hello
hello
icannotacit
Giveup
样例输出
3
0
0

PS:
因为‘+’的ASCII值是43,‘@’的是64,小写字母的是97-122之间,‘+’与‘z’相差80,所以每次开辟空间的时候要开辟80个新的空间。如果只是26个单词的话需要开辟26个空间即可。

字典树的分析:
http://blog.csdn.net/zzran/article/details/7991942

字典树模板:

#include<iostream>#include<string.h>using namespace std;#define maxn 80struct node{    int cnt;    struct node *next[maxn]; //指向各个子树的指针};node *root;node* build(){    node *p=new node;    p->cnt=0;    for(int i=0;i<maxn;i++)        p->next[i] =NULL; //新建结点的子节点为空    return p;}int insert(char *s){    node *p=root;    int len=strlen(s);    for(int i=0;i<len;i++){        if(p->next [s[i]-'+']!=NULL)//s[i]-'+'表示i相对于+的相对位置            p=p->next [s[i]-'+']; //指针向下移动,链表的插入        else{        p->next [s[i]-'+']=build();          p=p->next [s[i]-'+'];        }    }    return p->cnt++;}int search(char *s){    int len=strlen(s);    node *p=root;    for(int i=0;i<len;i++){        if(p->next [s[i]-'+']!=NULL)            p=p->next [s[i]-'+'];        else return 0;    }    return p->cnt ;}int main(){    int n,m,t,i;    char s1[20],s2[20];    cin>>t;    while(t--){        root=build(); //建立根结点        cin>>n>>m;        getchar();        for(i=0;i<n;i++){            gets(s1);            insert(s1);        }        for(i=0;i<m;i++){            gets(s2);            int ans=search(s2);            cout<<ans<<endl;        }    }    return 0;}
原创粉丝点击