码迷,mamicode.com
首页 > 其他好文 > 详细

HDU1251统计难题---Trie Tree

时间:2017-05-30 15:47:03      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:log   strlen   bre   images   位置   hdu   tree   arc   img   

 

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(红黑树),对于此类问题,字典树效率优势明显

 

HDU1251统计难题---Trie Tree

标签:log   strlen   bre   images   位置   hdu   tree   arc   img   

原文地址:http://www.cnblogs.com/kimsimple/p/6920147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!