HDU1251统计难题---Trie Tree


map巧过

#include <stdio.h>
#include <string.h>
#include <map>
#include <string>
using namespace std;
map<string,int>m1;
int main()
{
    char z[10];
    while(gets(z))
    {
        if(strlen(z)==0)
            break;
        for(int i=strlen(z);i>0;i--)
        {
            z[i]='\0';
            m1[z]++;
        }
    }
    while(gets(z))
    {
        printf("%d\n",m1[z]);
    }
    return 0;
}

经典前缀树

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;

struct node
{
    int Count;///以此节点为前缀的单词数
    node *next[26];///26叉树
    node() ///初始化数据
    {
        for (int i=0;i<26;i++)
            next[i]=NULL;
        Count=0;
    }
};

node *p,*root=new node();
void Insert(char *s)///插入新单词,即建立字典树
{
    int i,k;
    p=root;
    for (i=0; s[i]!='\0'; i++)
    {
        k=s[i]-'a';
        if (p->next[k]==NULL)
            p->next[k]=new node();
    ///判断是不是新节点,如果是分配创建一个新节点来存贮 ,
    ///即root的next域对应的k位置是否为空
        p=p->next[k];///向前走一步
        p->Count++; ///以此位置为前缀的数量+1
    }
}

int Search(char *s)
{
    int i,k;
    p=root;
    for (i=0; s[i]!='\0'; i++)
    {
        k=s[i]-'a';
        if (p->next[k]==NULL)///一旦查找不到,立即跳出
            return 0;
        p=p->next[k];
    }
    return p->Count;
}

int main()
{
    char s[11];
    while (gets(s))
    {
        int len=strlen(s);
        if (len==0)
            break;
        Insert(s);
    }
    while (gets(s))
    {
        printf("%d\n",Search(s));
    }
    return 0;
}


第一个字典树(G++内存超限),第二个map(红黑树),对于此类问题,字典树效率优势明显



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值