n=1时tle是为什么呢
查看原帖
n=1时tle是为什么呢
206423
焚魂楼主2024/9/29 15:40

RT

#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int n,ans,ch[3000010][30],tot = 1,bo[3000010],que[3000010],nxt[3000010];
char input[3000010];

void insert(char *s) {
    int u = 1,len = strlen(s);
    for(int i = 0;i < len;i++) {
        int c = s[i] - 'a';
        if(!ch[u][c]) ch[u][c] = ++tot;
        u = ch[u][c];
    }
    bo[u]++;
}

void bfs() {
    for(int i = 0;i <= 25;i++)
        ch[0][i] = 1;
    que[1] = 1; nxt[1] = 0;
    for(int q1 = 1,q2 = 1;q1 <= q2;++q1) {
        int u = que[q1];
        for(int i = 0;i <= 25;i++) {
            if(!ch[u][i]) ch[u][i] = ch[nxt[u]][i];
            else {
                que[++q2] = ch[u][i];
                int v = nxt[u];
                while(v > 0 && !ch[v][i]) v = nxt[v];
                nxt[ch[u][i]] = ch[v][i];
            }
        }
    }
}

void find(char *s) {
    int u = 1,len = strlen(s);
    for(int i = 0;i < len;i++) {
        int c = s[i] - 'a';
        int k = ch[u][c];
        while(k > 1) {
            ans += bo[k];
            bo[k] = 0;
            k = nxt[k];
        }
        u = ch[u][c];
    }
    return;
}

int main() {
    cin >> n;
    for(int i = 1;i <= n;i++) {
        cin >> input;
        insert(input);
    }
    bfs();
    cin >> input;
    find(input);
    cout << ans;

    return 0;
}
2024/9/29 15:40
加载中...