统计难题 (字典树)

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

Input

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

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

Output

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

Sample Input

banana
band
bee
absolute
acm

ba
b
band
abc

Sample Output

2
3
1
0

PS:这是一道裸的线段树的题,但是由于数据不大,用map分解单词,这个题也能过,不过字典树的时间复杂度很小,但是交字典树的代码用c++,用G++交的话要超内存,这是一个很有趣的现象,要是有大佬知道为什么,就评论在下面吧,谢谢。

map AC代码:

#include<cstdio>
#include<map>
#include<cstring>
using namespace std;
map<string,int>mp;
int main()
{
	char str[12];
    while(gets(str)&&strlen(str))
    {
    	for(int i=strlen(str);i>0;i--)
    	{
    		str[i]='\0';
    		mp[str]++;
		}
	}
    while(gets(str))
        printf("%d\n",mp[str]);
	return 0;
}

字典树 AC代码:

#include <iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<map>
#include<queue>
#include<set>
#include<cmath>
#include<stack>
#include<string>
const int maxn=2e5+5;
const int mod=1e9+7;
const int inf=1e9;
#define me(a,b) memset(a,b,sizeof(a))
typedef long long ll;
using namespace std;
struct node
{
    int s;
    node *next[26];
    node()
    {
        s=0;
        me(next,NULL);
    }
};
node *root=new node();
void insert(char *c)
{
    node *p=root;
    for(int i=0;i<strlen(c);i++)
    {
        int k=c[i]-'a';
        if(p->next[k]==NULL)
            p->next[k]=new node();
        p=p->next[k];
        p->s++;
    }
}
int search(char *c)
{
    node *p=root;
    for(int i=0;i<strlen(c);i++)
    {
        int k=c[i]-'a';
        if(p->next[k]==NULL)
           return 0;
        p=p->next[k];
    }
    return p->s;
}
int main()
{
    char str[15];
    while(gets(str)&&strlen(str))
        insert(str);
    while(gets(str))
        printf("%d\n",search(str));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41292370/article/details/81303427
今日推荐