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

[hdu1251]统计难题(trie模板题)

时间:2019-02-04 09:01:50      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:name   for   字符串   har   root   结构   insert   ios   gets   

题意:返回字典中所有以测试串为前缀的字符串总数。

解题关键:trie模板题,由AC自动机的板子稍加改造而来。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include<queue>
using namespace std;
typedef long long ll;
const int N=26;
const int MAXN=520000;
struct Trie{//数组形式
    int Next[MAXN][N],Fail[MAXN],End[MAXN],root,tot;//大小为所以匹配字符串的总和
    int newnode(){//结构体内部用
        for(int i=0;i<N;i++) Next[tot][i]=-1;
        End[tot++]=0;
        return tot-1;
    }
    void init(){
        tot=0;
        root=newnode();
    }
    void insert(char buf[]){
        int len=strlen(buf);
        int now=root;//now是temp指针
        for(int i=0;i<len;i++){
            int k=buf[i]-a;
            if(Next[now][k]==-1)  Next[now][k]=newnode();//next数组代表的是下一个字符索引
            now=Next[now][k];
            End[now]++;
        }
    }
    int fnd(char buf[]){
        int len=strlen(buf);
        int now=root;//now是temp指针
        for(int i=0;i<len;i++){
            int k=buf[i]-a;
            if(Next[now][k]==-1)  return 0;//next数组代表的是下一个字符索引
            now=Next[now][k];
        }
        return End[now];
    }
};
Trie ac;
char buf[20];
int main(){
    ac.init();
    while(gets(buf)){
        if(buf[0]==NULL)break;//gets读入的回车会自动转化为NULL
        ac.insert(buf);
    }
    while(gets(buf)){
        printf("%d\n",ac.fnd(buf));
    }
    return 0;
}

 

[hdu1251]统计难题(trie模板题)

标签:name   for   字符串   har   root   结构   insert   ios   gets   

原文地址:https://www.cnblogs.com/elpsycongroo/p/10351368.html

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