hdu1251 统计难题(字典树)

握日啊,这题用G++提交就算释放了内存都MLE,害的我纠结了好几天。

模板题吧,感觉自己对结构体的用法还不是很灵活,加油吧。


#include <stdio.h>
#include <algorithm>
#include <map>
#include <stdlib.h>
#include <string.h>

using namespace std;

typedef long long LL;

const int N = 15;
const int INF = 1e8;

struct Trie
{
    int sum;
    Trie *next[26];
}*root;

void CreatTrie(char *str)
{
    int len = strlen(str);
    Trie *p = root, *q;
    for(int i = 0; i < len; i ++)
    {
        int id = str[i] - 'a';
        if(p -> next[id] == NULL)
        {
            q = new Trie;
            q -> sum = 1;
            for(int j = 0; j < 26; j ++)
            {
                q -> next[j] = NULL;
            }
            p -> next[id] = q;
            p = p -> next[id];
        }
        else
        {
            p -> next[id] -> sum ++;
            p = p -> next[id];
        }
    }
}

int FindTrie(char *str)
{
    Trie *p;
    int len = strlen(str);
    p = root;
    for(int i = 0; i < len; i ++)
    {
        int id = str[i] - 'a';
        p = p -> next[id];
        if(p == NULL) return 0;
    }
    return p -> sum;
}

void Release(Trie *p)
{
    if(p == NULL) return;
    for(int i = 0; i < 26; i ++)
        if(p -> next[i] != NULL) Release(p -> next[i]);
    free(p);
    root = NULL;
    return;
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    int t, num;
    char s[N], str[N];
    root = new Trie;
    root -> sum = 0;
    for(int i = 0; i < 26; i ++)
    {
        root -> next[i] = NULL;
    }
    while(gets(s) && s[0] != '\0')
    {
        CreatTrie(s);
    }
    while(~scanf("%s", str))
    {
        int ans = FindTrie(str);
        printf("%d\n", ans);
    }
    Release(root);
    return 0;
}

后来想了想还是这个模板更加简洁。


#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

typedef long long LL;

const int N = 15;
const int INF = 1e8;

struct Trie
{
    int sum;
    bool exist;
    Trie *next[26];
    Trie()
    {
        exist = 0;
        sum = 0;
        for(int i = 0; i < 26; i ++)
            next[i] = 0;
    }
}root;

void inserttrie(char *str)
{
    int k = 0;
    Trie *p = &root;
    while(str[k] != '\0')
    {
        int id = str[k] - 'a';
        if(p -> next[id] == 0) p -> next[id] = new Trie;
        p = p -> next[id];
        p -> sum ++;
        k ++;
    }
    p -> exist = 1;
}

int findtrie(char *str)
{
    int k = 0;
    Trie *p = &root;
    while(str[k] != '\0' && p -> next[str[k] - 'a']) p = p -> next[str[k ++] - 'a'];
    return str[k] == '\0' ? p -> sum : 0;
}

int main()
{
  //  freopen("in.txt", "r", stdin);
    char s[N];
    while(gets(s) && s[0] != '\0') inserttrie(s);
    while(~scanf("%s", s)) printf("%d\n", findtrie(s));
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值