模板(字符串)

2 篇文章 0 订阅

ac自动机

//UVALive 4670	
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <string>
using namespace std;

const int MAXN = 21000;
const int MAXM = 1000001;
const int INF = 1 << 30;
const int SEGMA_SZ = 26;

int ch[MAXN][SEGMA_SZ],cnt;
int pre[MAXN],isWord[MAXN],lastWord[MAXN];
int calc[MAXN],n,maxTime;
char s[MAXM];
map<int, string> hash;

void init(){
    memset(ch[0], 0, sizeof(ch[0])); cnt=0;
    memset(calc, 0 ,sizeof(calc));
    hash.clear();
    maxTime=0;
}

void Insert(char s[],int id){
    int u=0;
    for (int i = 0; s[i]; ++i){
        int v = s[i] - 'a';
        if (!ch[u][v]){
            cnt++;
            memset(ch[cnt], 0, sizeof(ch[cnt]));
            isWord[cnt] = lastWord[cnt] = 0;
            ch[u][v] = cnt;
        }
        u = ch[u][v];
    }
    isWord[u] = id;
}

queue<int> q;
void getPre(){
    while (!q.empty()) q.pop();
    pre[0]=0;

    for (int i = 0; i < SEGMA_SZ; ++i)
        if (ch[0][i]){
            int v = ch[0][i];
            pre[v] = 0;
            q.push(v);
        }

    while (!q.empty()){
        int u = q.front(); q.pop();
        for (int i = 0; i < SEGMA_SZ; ++i){
            int v = ch[u][i];
            if (!v) continue;
             q.push(v);

            int tmp_pre = pre[u];
            while (tmp_pre && !ch[tmp_pre][i])
                tmp_pre = pre[tmp_pre];
            pre[v]=ch[tmp_pre][i];

            lastWord[v] = isWord[pre[v]] ? pre[v] : lastWord[pre[v]];
        }
    }
}

void Find(char s[]){
    int j = 0;
    for (int i = 0; s[i]; ++i){
        int v = s[i] - 'a';
        while (j && !ch[j][v]) j = pre[j];
        j = ch[j][v];

        int tmp_pre=j;
        do{
            calc[isWord[tmp_pre]]++;
            tmp_pre = lastWord[tmp_pre];
            if (!tmp_pre) break;
        }while (1);
    }
    for (int i = 1; i <= n; ++i)
        maxTime = max(maxTime, calc[i]);
}

int main(){
    while (~scanf("%d", &n) && n ){
        init();
        for (int i = 1; i <= n; ++i){
            scanf("%s", s);
            hash[i]=string(s);
            calc[i]=0;
            Insert(s, i);
        }
        scanf("%s", s);
        getPre();

        Find(s);
        printf("%d\n", maxTime);
        for(int i = 1; i <= n; ++i)
            if (calc[i] == maxTime)
                cout << hash[i] << endl;
    }
    return 0;
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值