bzoj3473: 字符串

Description
给定n个字符串,询问每个字符串有多少子串(不包括空串)是所有n个字符串中至少k个字符串的子串?
Input
第一行两个整数n,k。
接下来n行每行一个字符串。
Output
一行n个整数,第i个整数表示第i个字符串的答案。
Sample Input
3 1
abc
a
ab
Sample Output
6 1 3
HINT
对于 100% 的数据,1<=n,k<=10^5,所有字符串总长不超过10^5,字符串只包含小写字母。
Source
Adera 1 杯冬令营模拟赛

用广义SAM做..

用set维护到达当前点所属串的个数,顺着fail启发式合并到根

询问的时候,每走到一个点表示的是这个串的前缀,而我们要统计的就是这个前缀最长后缀使得这个后缀符合条件,然后ans加上这个最长后缀长度就好了,因为1~最长后缀都可以到达..

#include 
#include 
#include 
#include 
#include 
#define LL long long
using namespace std;
const LL Maxn = 100010;
const LL lg = 20;
LL F[Maxn*2], d[Maxn*2], ch[Maxn*2][26], tot, now, f[Maxn*2];
char s[Maxn*2]; LL len;
LL Rsort[Maxn*2], rk[Maxn*2];
LL n, K;
set  S[Maxn*2];
set  :: iterator it;
LL copy ( LL p, LL c ){
    LL x = ++tot, y = ch[p][c];
    d[x] = d[p]+1;
    for ( LL i = 0; i < 26; i ++ ) ch[x][i] = ch[y][i];
    F[x] = F[y]; F[y] = x;
    while ( ~p && ch[p][c] == y ){ ch[p][c] = x; p = F[p]; }
    return x;
}
void add ( LL c ){
    LL p, o;
    if ( p = ch[now][c] ){
        if ( d[p] != d[now]+1 ) copy ( now, c );
        now = ch[now][c];
    }
    else {
        d[o=++tot] = d[now]+1; p = now; now = o;
        while ( ~p && !ch[p][c] ){ ch[p][c] = o; p = F[p]; }
        F[o] = ~p ? ( d[p]+1 == d[ch[p][c]] ? ch[p][c] : copy ( p, c ) ) : 0;
    }
}
void merge ( LL x, LL y ){
    while ( S[y].begin () != S[y].end () ){
        it = S[y].begin ();
        S[x].insert (*it);
        S[y].erase (it);
    }
}
LL _max ( LL x, LL y ){ return x > y ? x : y; }
int main (){
    LL i, j, k;
    scanf ( "%lld%lld", &n, &K );
    len = 0;
    for ( i = 1; i <= n; i ++ ){
        scanf ( "%s", s+len );
        len = strlen (s);
        s[len++] = '$';
    }
    F[0] = -1; now = 0;
    LL ss = 0;
    for ( i = 0; i < len; i ++ ){
        if ( s[i] != '$' ){ add (s[i]-'a'); S[now].insert (ss); }
        else { now = 0; ss ++; }
    }
    for ( i = 1; i <= tot; i ++ ) Rsort[d[i]] ++;
    for ( i = 1; i <= len; i ++ ) Rsort[i] += Rsort[i-1];
    for ( i = tot; i >= 1; i -- ) rk[Rsort[d[i]]--] = i;
    for ( i = tot; i >= 1; i -- ){
        if ( S[rk[i]].size () >= K ) f[rk[i]] = d[rk[i]];
        merge ( F[rk[i]], rk[i] );
    }
    for ( i = 1; i <= tot; i ++ ) f[rk[i]] = _max ( f[F[rk[i]]], f[rk[i]] );
    j = 0;
    for ( i = 1; i <= n; i ++ ){
        if ( s[j] == '$' ) j ++;
        now = 0; LL ans = 0;
        while ( s[j] != '$' ){
            LL c = s[j]-'a';
            now = ch[now][c];
            ans += f[now];
            j ++;
        }
        printf ( "%lld ", ans );
    }
    printf ( "\n" );
    return 0;
}

你可能感兴趣的:(SAM,bzoj)