bzoj3473: 字符串

本文介绍了一种使用广义SAM算法解决字符串问题的方法,具体为统计每个字符串中有多少子串是所有字符串中至少k个字符串的子串。通过实例演示了如何构建SAM自动机,并利用启发式合并和广义SAM来高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
### BZOJ1461 字符串匹配 题解 针对BZOJ1461字符串匹配问题,解决方法涉及到了KMP算法以及树状数组的应用。对于此类问题,朴素的算法无法满足时间效率的要求,因为其复杂度可能高达O(ML²),其中M代表模式串的数量,L为平均长度[^2]。 为了提高效率,在这个问题中采用了更先进的技术组合——即利用KMP算法来预处理模式串,并通过构建失配树(也称为失败指针),使得可以在主串上高效地滑动窗口并检测多个模式串的存在情况。具体来说: - **前缀函数与KMP准备阶段**:先对每一个给定的模式串执行一次KMP算法中的pre_kmp操作,得到各个模式串对应的next数组。 - **建立失配树结构**:基于所有模式串共同构成的一棵Trie树基础上进一步扩展成带有失配链接指向的AC自动机形式;当遇到某个节点不存在对应字符转移路径时,则沿用该处失配链路直至找到合适的目标或者回到根部重新开始尝试其他分支。 - **查询过程**:遍历整个待查文本序列的同时维护当前状态处于哪一层级下的哪个子结点之中,每当成功匹配到完整的单词就更新计数值至相应位置上的f_i变量里去记录下这一事实。 下面是简化版Python代码片段用于说明上述逻辑框架: ```python from collections import defaultdict def build_ac_automaton(patterns): trie = {} fail = [None]*len(patterns) # 构建 Trie 树 for i,pattern in enumerate(patterns): node = trie for char in pattern: if char not in node: node[char]={} node=node[char] node['#']=i queue=[trie] while queue: current=queue.pop() for key,value in list(current.items()): if isinstance(value,int):continue if key=='#': continue parent=current[key] p=fail[current is trie and 0 or id(current)] while True: next_p=p and p.get(key,None) if next_p:break elif p==0: value['fail']=trie break else:p=fail[id(p)] if 'fail'not in value:value['fail']=next_p queue.append(parent) return trie,fail def solve(text, patterns): n=len(text) m=len(patterns) f=[defaultdict(int)for _in range(n)] ac_trie,_=build_ac_automaton(patterns) state=ac_trie for idx,char in enumerate(text+'$',start=-1): while True: trans=state.get(char,state.get('#',{}).get('fail')) if trans!=None: state=trans break elif '#'in state: state[state['#']['fail']] else: state=ac_trie cur_state=state while cur_state!={}and'#'in cur_state: matched_pattern_idx=cur_state['#'] f[idx][matched_pattern_idx]+=1 cur_state=cur_state['fail'] result=[] for i in range(len(f)-1): row=list(f[i].values()) if any(row): result.extend([sum((row[:j+1]))for j,x in enumerate(row[::-1])if x>0]) return sum(result) patterns=["ab","bc"] text="abc" print(solve(text,text)) #[^4] ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值