HDU 1251 字典树


题意:给你一系列单词库,接下来给你一些单词,询问有多少以该字符串为前缀的单词的数量.



#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
#define INF 1e8
#define eps 1e-8
#define LL long long
#define maxn 26
#define mol 1000000007
char s[110];

struct Trie
{
   Trie *next[maxn];
   int v;
}root;
void creatTrie(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->v=1;
		for(int j=0;j<maxn;j++)
		    q->next [j]=NULL;
		p->next [id]=q;
		p=q;
	  }
	  else
	  {
		 p=p->next[id];
		 p->v++;
	  }
   }
}
int find (char *str)
{
    int len = strlen(str);
	Trie *p=&root;
	for(int i=0;i<len;i++)
	{
	    int id = str[i]-'a';
		if(p->next[id])
		p = p->next[id];
		else return 0;
	}
	return p->v ;

}
int main()
{
	int i,n=0;
	char ch[20];
	for(i=0;i<maxn;i++)
		root.next [i]=NULL;
	while(gets(s)&&s[0]!='\0')
	   creatTrie(s);
	while(gets(ch))
	    printf("%d\n",find(ch));
return 0;
}
/*
banana
band
bee
absolute
acm

ba
b
band
abc
*/


你可能感兴趣的:(HDU 1251 字典树)