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

HDU-1251统计难题 ,字典树

时间:2018-05-06 00:13:43      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:int   algorithm   max   stream   str   题意   字典   ios   char   

题意:问许多单词中,前缀是某个字符串的个数有多少个;

思路:  用字典树建立,每个节点带上num,记录每次insert是,经过这个点的次数,

   每次询问,找到这个前缀对应的节点的num就ok

这道题,c++过,g++不行

ac代码:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <cstdio>
using namespace std;

const int maxn = 500000;
struct node {
    node * s[26];
    int num;
};

node a[maxn],*rt;
int p = 0;
char str[11];

node * newNode()
{
    memset(a[p].s,0,sizeof(a[p].s));
    a[p].num = 0;
    return &a[p++];
}

void insert(char * str)
{
    node * cur = rt;
    cur->num++;
    while( *str != \0)
    {
        int t = *(str++) - a;
        if(cur->s[t]==0)
            cur-> s[t]=newNode();
        cur = cur->s[t];
        cur -> num++;
    }
}

int getans(char *str)
{
    node *cur = rt;
    while(*str!=\0)
    {
        int t = *(str++) - a;
        if(cur->s[t]==0)return 0;
        cur  = cur -> s[t]; 
    }
    return cur->num;
}

int main(){        
    rt = newNode();
    gets(str);
    while(str[0]!=\0)
    {
        insert(str);
        gets(str);
    }
    while(~scanf("%s",str))
    {
        printf("%d\n",getans(str));
    }
    return 0;
}

 

HDU-1251统计难题 ,字典树

标签:int   algorithm   max   stream   str   题意   字典   ios   char   

原文地址:https://www.cnblogs.com/ckxkexing/p/8996714.html

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