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 <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <set>
#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 <LL> S[Maxn*2];
set <LL> :: 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;
}