hdu1251统计难题(字典树小试牛刀)

->题目猛戳这里<-

题目大意:略

题目分析:建棵字典树就ok,详情请见代码:

#include <iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
using namespace std;

char s[20];
typedef struct node
{
    struct node *next[26];
    int num;
}tree;

void init(tree *t)
{
	t->num = 0;
	for(int i = 0;i < 26;i ++)
		t->next[i] = NULL;
}

void build(tree *t,int id)
{
    if(t->next[s[id] - 'a'] == NULL)
    {
        t->next[s[id] - 'a'] = (tree *)malloc(sizeof(tree));
        init(t->next[s[id] - 'a']);
        t->next[s[id] - 'a']->num = 1;
    }
    else
    {
        t->next[s[id] - 'a']->num ++;
    }
    if(s[id + 1] == '\0')
        return;
    else
        build(t->next[s[id] - 'a'],id + 1);
}

int query(tree * t,int id)
{
    if(t->next[s[id] - 'a'] == NULL)
        return 0;
    if(s[id + 1] == '\0')
        return t->next[s[id] - 'a']->num;
    return query(t->next[s[id] - 'a'],id + 1);
}

int main()
{
    tree *root = NULL;
    root = (struct node *)malloc(sizeof(struct node));
    init(root);
    while(gets(s))
    {
        //puts(s);
        if(strlen(s) == 0)
            break;
        build(root,0);
    }
    while(gets(s) != NULL)
    {
        int ans;
        ans = query(root,0);
        printf("%d\n",ans);
    }
    return 0;
}
//140MS	43896K


你可能感兴趣的:(数据结构,字典树)