HDU 1251 Trie树模板题

时间:2022-03-30 21:34:14

1、HDU 1251 统计难题  Trie树模板题,或者map

2、总结:用C++过了,G++就爆内存。。

题意:查找给定前缀的单词数量。

#include<iostream>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
#include<cstdio>
#define max(a,b) a>b?a:b
#define F(i,a,b) for(int i=a;i<=b;i++)
#define mes(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
const int N=,MAX=; struct Node
{
int count;
Node *child[];
Node(){
mes(child,NULL);
count=;
}
}; Node *root=new Node,*current;
void insert(char *str)
{
current=root;
for(int i=;str[i];++i){
int m=str[i]-'a';
if(current->child[m]==NULL){
current->child[m]=new Node;
}
current=current->child[m];
current->count++;
}
} int search(char *str)
{
current=root;
for(int i=;str[i];++i){
int m=str[i]-'a';
if(current->child[m]==NULL)
return ;
current=current->child[m];
}
return current->count;
} int main()
{
char str[];
while(gets(str),*str)
insert(str);
while(gets(str))
printf("%d\n",search(str)); return ;
}