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

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

解题关键: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
",ac.fnd(buf));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/elpsycongroo/p/10351368.html