[TJOI2013] word

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_43544481/article/details/102755993

Title Description
someone reading the paper, a paper is composed of many words. But he found many times a word appears in the paper, and now want to know how many times each word appeared in the paper.

Input Description:
The first integer N, the number of words, followed by N lines of one word. Lowercase letters of each word, N ≤ 200, word length does not exceed 10 ^ 6

Output Description: The
output N integers, digital i-th row represents the i-word appeared many times in the article. ``

Only you need to build a fail tree, like a tree Praying

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MAXN = 1e6+50;
const int MOD = 1e9+7;
inline int read(){
    int x=0,f=1; char ch=getchar();
    while(!isdigit(ch)){ if(ch=='-') ch=-1; ch = getchar(); }
    while(isdigit(ch)) x=x*10+ch-48,ch=getchar();
    return x*f;
}
struct Trie{
    int nxt[MAXN][26],fail[MAXN],cnt[MAXN],id[MAXN];
    vector<int> g[MAXN];
    int sz;
    void Insert(char *s,int k){
        int root=0,len=strlen(s);
        for(int i=0;i<len;i++){
            if(!nxt[root][s[i]-'a']) nxt[root][s[i]-'a'] = ++sz;
            root = nxt[root][s[i]-'a'];
            cnt[root]++;
        }
        id[k] = root;
    }
    void Build(){
        queue<int> que;
        for(int i=0;i<26;i++) if(nxt[0][i]) que.push(nxt[0][i]);
        while(!que.empty()){
            int u = que.front(); que.pop();
            for(int i=0;i<26;i++){
                if(nxt[u][i]) {
                    que.push(nxt[u][i]);
                    fail[nxt[u][i]] = nxt[fail[u]][i];
                }
                else nxt[u][i] = nxt[fail[u]][i];
            }
        }
    }
    void dfs(int u){
        for(int i=0;i<(int)g[u].size();i++){
            int v = g[u][i];
            dfs(v);
            cnt[u] += cnt[v];
        }
    }
    void solve(int n){
        for(int i=1;i<=sz;i++) g[fail[i]].push_back(i);
        dfs(0);
        for(int i=1;i<=n;i++) printf("%d\n",cnt[id[i]]);
    }
}Automaton;
char str[MAXN];
int main(){
    int n = read();
    for(int i=1;i<=n;i++) scanf("%s",str),Automaton.Insert(str,i);
    Automaton.Build();
    Automaton.solve(n);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43544481/article/details/102755993