统计难题---hdu1251字典树模板

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1251

 

node *head=(node*)malloc(sizeof(node));
for(int i=0; i<26; i++)
{
   head->next[i] = NULL;
   head->sum = 0;
}
可以改成node *head=new node();
要用c++提交才对,不然G++就内存超限了-_-
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
using namespace std;

struct node
{
    int sum;
    node *next[26];
};

void BuildLibTree(node *head, char s[])
{
    node *p = head,*q;

    for(int i=0; s[i]; i++)
    {
        int k = s[i] - 'a';
        if(p->next[k] == NULL)
        {
            q=(node*)malloc(sizeof(node));
            for(int j=0; j<26; j++)
            {
                q->next[j] = NULL;
                q->sum = 0;
            }
            p->next[k] = q;
        }
        p = p->next[k];
        p->sum++;
    }
}
int Query(node *head, char s[])
{
    node *p = head;
    for(int i=0; s[i]; i++)
    {
        int k = s[i]-'a';
        if(p->next[k] == NULL)
            return 0;
        p = p->next[k];
    }
    return p->sum;
}
int main()
{
    char s[20];
    node *head=(node*)malloc(sizeof(node));
    for(int i=0; i<26; i++)
    {
        head->next[i] = NULL;
        head->sum = 0;
    }
    while(gets(s),s[0])
        BuildLibTree(head, s);

    while(scanf("%s",s)!=EOF)
        printf("%d\n", Query(head, s));
    return 0;
}

 

posted @ 2015-07-31 09:38  西瓜不懂柠檬的酸  Views(138)  Comments(0Edit  收藏  举报
levels of contents