【字典树】HDU1251统计难题

来源:互联网 发布:免费下载qq软件 编辑:程序博客网 时间:2024/06/05 07:17

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1251

用的是指针,指针不懂的就得好好先稍微懂一点指针在来轻松搞定;

这个博客写的还不错,可以推荐看一下。链接:http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html

#include<iostream>#include<string>#include<cstdio>#include<cstring>#include<map>#include<queue>#include<cmath>#include<stack>#include<set>#include<vector>#include<algorithm>#define LL long long#define inf 1<<29#define s(a) scanf("%d",&a)#define CL(a,b) memset(a,b,sizeof(a))using namespace std;const int maxn=26;  //  只有小写字母,所以26,大小写都有为52,加上数字为62;int n,m,a,b;struct node{    int cnt;    node * next[maxn];          //  单向链表;    node(){                     //  新节点初始化;        cnt=0;        memset(next,0,sizeof(next));    }};node *p,*head=new node();void Insert(char s[]){    p=head;    for(int i=0;s[i];i++){        int id=s[i]-'a';        //  将字母转换成对应的数字;        if(p->next[id]==NULL) p->next[id]=new node();       //  该该字母首次出现在该位置,新建节点,并初始化;        p=p->next[id];          //  往后移;        p->cnt++;               //  计数加一;    }}int Query(char s[]){    p=head;    for(int i=0;s[i];i++){        int id=s[i]-'a';        if(p->next[id]==NULL) return 0;     //  说明以该单词为前缀的单词不存在;        p=p->next[id];          //  往后移;    }    return p->cnt;}int main(){    char s[15];    //while(gets(s),strcmp(s,"")) Insert(s);    while(gets(s),*s) Insert(s);                //  *s的意思每次输入的长度大于0;    while(gets(s)) printf("%d\n",Query(s));    return 0;}


 

1 0
原创粉丝点击