bzoj 4566 [Haoi2016]找相同字符——广义后缀自动机

本文详细解析了AC自动机与拓扑排序动态规划的结合应用,通过一个具体的算法题,介绍了如何利用自动机节点贡献计算两个字符串中匹配子串的数量,以及如何通过拓扑排序优化DP过程。

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

题目:https://www.lydsy.com/JudgeOnline/problem.php?id=4566

每个后缀结尾处 ct[ ] = 1 ,按拓扑序 dp 一下就能求出 right 集合的大小。自动机上每个点的贡献就是 ( l [cr]-l [fa] ) * ct[0][cr] * ct[1][cr] , ct[0] 和 ct[1] 表示在两个字符串里分别的出现次数。

#include<cstdio>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
const int N=2e5+5,M=8e5+5,K=30;
int tot=1,go[M][K],fa[M],l[M],ct[2][M],ans[M];
char s[2][N]; int q[M],tx[N],vis[M];
int cz(int p,int w)
{
  int q=go[p][w],nq=++tot;l[nq]=l[p]+1;
  fa[nq]=fa[q];fa[q]=nq;
  memcpy(go[nq],go[q],sizeof go[q]);
  for(;p&&go[p][w]==q;p=fa[p])go[p][w]=nq;
  return nq;
}
int ins(int p,int w)
{
  if(go[p][w])
    {
      int q=go[p][w];
      if(l[q]==l[p]+1)return q; return cz(p,w);
    }
  int np=++tot;l[np]=l[p]+1;
  for(;p&&!go[p][w];p=fa[p])go[p][w]=np;
  if(!p)fa[np]=1;
  else
    {
      int q=go[p][w];
      if(l[q]==l[p]+1)fa[np]=q;
      else fa[np]=cz(p,w);
    }
  return np;
}
void Rsort(int n)
{
  for(int i=1;i<=tot;i++)tx[l[i]]++;
  for(int i=1;i<=n;i++)tx[i]+=tx[i-1];
  for(int i=1;i<=tot;i++)q[tx[l[i]]--]=i;
}
int main()
{
  scanf("%s",s[0]);scanf("%s",s[1]);
  int n[2];n[0]=strlen(s[0]);n[1]=strlen(s[1]);
  for(int t=0;t<=1;t++)
    for(int pr=1,i=0;i<n[t];i++)pr=ins(pr,s[t][i]-'a'),ct[t][pr]=1;
  Rsort(max(n[0],n[1])); ll prn=0;
  for(int i=tot,d;i;i--)
    {
      for(int t=0;t<=1;t++)ct[t][fa[d=q[i]]]+=ct[t][d];
      prn+=(ll)(l[d]-l[fa[d]])*ct[0][d]*ct[1][d];
    }
  printf("%lld\n",prn);
  return 0;
}

 

转载于:https://www.cnblogs.com/Narh/p/10291156.html

### 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、付费专栏及课程。

余额充值