hdu 1251 统计难题(tire 树 模版题)

题意:统计以某个字符串为前缀的单词的数量。

思路:字典树,建树的同时统计,节点字符的个数

#include<iostream>
#define max 26
using namespace std;
struct node
{
  int count;//记录此节点字串的个数 
  node *next[max];//子节点 
  node()//构造函数   new node()时候自动执行 
  {
    count=1;
    for(int i=0;i<max;i++)
    next[i]=NULL;
  }
};
void insert(node *&root,char *word)
{
   node *l=root;
   int i=0,branch=0;
   //if(l==NULL) { l=new node();root=l;} 
   while(word[i]!='\0')
   {
     branch=word[i]-'a';
     if(l->next[branch]) {l->next[branch]->count++;}//下一个节点如果不是NULL 则下一个节点的count +1
     else l->next[branch]=new node();//一个节点如果是NULL 则开辟新的节点 
     l=l->next[branch];//指针指向本身的NEXT 也就是下一个节点 
     i++;
   }
}
int search(node *root,char *word)//与查找类似 
{
   node *l=root;
   int i=0,branch=0,ans;
   //if(l==NULL) return 0;
   while(word[i]!='\0')
   {
     branch=word[i]-'a';
     if(l->next[branch]){l=l->next[branch];ans=l->count;}
     else return 0;
     i++;
   }
   return ans;
}
int main()
{
  char word[100],b[10];
  //node *root=NULL;
  node *root=new node();
  while(gets(word))
  {
   if(word[0]=='\0') break;
   insert(root,word);
  }
  while(gets(b))
  printf("%d\n",search(root,b));
  //system("pause");
  return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值