bzoj 3172: [Tjoi2013]单词

 fail 树的应用

一个节点代表的是一个字符串的前缀,那么我们首先需要统计每一个节点作为前缀出现了多少次。

然后,一个节点在fail树上的后代节点代表的是这个前缀是某一个前缀的后缀,那么这个单词一定也会出现在这些后缀中。

所以我们需要把后代节点的贡献也加到这个节点中。

建立AC自动机时节点的入队的顺序反过来就可以统计了。

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2000000;
const int N = 2000000;
int ch[N][26],tot,f[N],cnt[N],val[N],last[N];
void init(int n){
    tot = 0;
    memset( ch[0],0,sizeof( ch[0] ) );
}
void Insert( char* str ){
    int p = 0;int n = strlen( str );
    for( int i = 0;i < n;i++ ){
        int c = str[i]-'a';
        if( !ch[p][c] )  {
            ch[p][c] = ++tot;val[tot]= 0;last[tot] = 0;
            memset( ch[tot],0,sizeof( ch[tot] ) );
        }
        p = ch[p][c];
        cnt[p]++;
    }
    val[p] = 1;
}
queue<int> que;
stack<int> st;
void getfail(){
    for( int i = 0;i < 26;i++ ){
        if( ch[0][i] ) que.push( ch[0][i] );
    }
    while(que.size()){
        int x = que.front();st.push(x);
        que.pop();
        for( int c = 0;c < 26;c++ ){
            if( !ch[x][c] ){
                ch[x][c] = ch[ f[x] ][c];
                continue;
            }
            f[ ch[x][c] ] = ch[ f[x] ][c];
            last[ch[x][c]] = val[ f[ ch[x][c] ] ] ? f[ch[x][c]] : last[ f[ ch[x][c] ] ];
            que.push(ch[x][c]);
        }
    }
}
char str[maxn];
int dp[maxn],ans;
int find( const char* str ){
    int n = strlen(str);
    int p = 0;
    for( int i = 0;i < n;i++ ){
        int c = str[i]-'a';
        p = ch[p][c];
    }
    return cnt[p];
}
vector<string> ve;
int main(){
    int n;
    scanf("%d",&n);
    for( int i = 1;i <= n;i++ ){
        scanf("%s",str);
        ve.push_back( string(str) );
        Insert(str);
    }
    getfail();
    while( st.size() ){
        int x=  st.top();
        st.pop();
        cnt[ f[x] ] += cnt[x];
    }
    for( int i = 0;i < n;i++ ){
        ans = find( ve[i].c_str() );
        printf("%d\n",ans);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值