HDU

来源:互联网 发布:三体读后感知乎 编辑:程序博客网 时间:2024/06/09 14:35

字典树模板题

G++ Memory Limit Exceeded

C++ Accepted

#include<stdio.h>#include<string.h>#include<stdlib.h>#include<algorithm>#include<iostream>using namespace std;struct node{int num;node *next[26];node(){num=0;for(int i=0;i<26;i++)next[i]=NULL;}};node *root=new node;node *head,*tail;void update(char *s){int i,m;head=root;for(i=0;i<strlen(s);i++){m=s[i]-'a';if(head->next[m]!=NULL){head=head->next[m];++(head->num);}else{tail=new node;++(tail->num);head->next[m]=tail;head=tail;}}}int query(char *s){int i,m;head=root;for(i=0;i<strlen(s);i++){m=s[i]-'a';if(head->next[m]==NULL)return 0;head=head->next[m];}return head->num;}int main(void){int i,j,k,n,m;char s[20];while(gets(s),strcmp(s,""))update(s);while(gets(s)!=NULL)printf("%d\n",query(s));return 0;}

原创粉丝点击