模板(字符串)

来源:互联网 发布:不会英语怎么学编程 编辑:程序博客网 时间:2024/06/10 01:06

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
原创粉丝点击