codeforces 802I 后缀自动机
来源:互联网 发布:微创软件 外派 编辑:程序博客网 时间:2024/05/18 01:41
题意:给你一个字符串,统计他的所有不同子串的出现次数的平方和,
其实相当于一个SAM的模板题吧。
首先你要理解SAM的存储方式以后就可以轻松切这题。。
SAM建立了一个parent树还有一个DAG,这里显然和DAG没什么关系。
对于parent树上的每个节点,他有一个right集,存储这一些子串的右端点下标,同时还有一个对应区间
那么对于一个right集合中的每一个长度len,他和所有右端点配对以后形成的子串是一样的,这意味着right集合的大小就是这个长度为len的子串的出现次数。。
那么这个right集合的大小就是
right集的大小很容易算,至于
不知道为什么代码不高亮了,辣鸡csdn。。建议贴回自己编译器里面。
#include<iostream>#include<cstdio>#include<cstring>#include<cstdlib>#include<algorithm>#include<cmath>#define N 500005#define ll long longusing namespace std;char s[N];int S,cnt,last;int a[N],b[N],f[N],t[N],fa[N],l[N],r[N],ch[N][26];void add(int x){ int c=a[x]; int p=last,np=++cnt;last=np; l[np]=x; for(;p&&!ch[p][c];p=fa[p])ch[p][c]=np; if(!p)fa[np]=S; else { int q=ch[p][c]; if(l[p]+1==l[q])fa[np]=q; else { int nq=++cnt;l[nq]=l[p]+1; memcpy(ch[nq],ch[q],sizeof ch[q]); fa[nq]=fa[q]; fa[np]=fa[q]=nq; for(;ch[p][c]==q;p=fa[p])ch[p][c]=nq; } }}int main(){ int cas; scanf("%d",&cas); while (cas--) { cnt=0; memset(r,0,sizeof(r)); memset(l,0,sizeof(l)); memset(ch,0,sizeof(ch)); memset(fa,0,sizeof(fa)); memset(t,0,sizeof(t)); scanf("%s",s+1); last=S=++cnt; int len=strlen(s+1); for(int i=1;i<=len;i++)a[i]=s[i]-'a'; for(int i=1;i<=len;i++)add(i); for(int i=1,p=S;i<=len;i++) { p=ch[p][a[i]];r[p]++; } for(int i=1;i<=cnt;i++)b[i]=0; for(int i=1;i<=cnt;i++)b[l[i]]++; for(int i=1;i<=len;i++)b[i]+=b[i-1]; for(int i=1;i<=cnt;i++)t[b[l[i]]--]=i; for(int i=cnt;i;i--)r[fa[t[i]]]+=r[t[i]]; //for(int i=1;i<=cnt;i++)f[l[i]]=max(f[l[i]],r[i]); //for(int i=len;i;i--)f[i]=max(f[i+1],f[i]); long long ans=0; for(int i=1;i<=cnt;i++)ans+=(long long)r[i]*r[i]*(l[i]-l[fa[i]]); printf("%lld\n",ans); } return 0;}
阅读全文
0 0
- codeforces 802I 后缀自动机
- 后缀自动机合集 I
- CodeForces 128B --后缀自动机
- [Codeforces][后缀自动机]Helvetic Coding Contest 2017 . I Fake News (hard)
- codeforces 123 D String(后缀自动机 SAM)
- codeforces 127D Password (后缀自动机 SAM)
- Codeforces 235C Cyclical Quest 后缀自动机
- Codeforces 235C. Cyclical Quest 后缀自动机
- 【后缀自动机】 CodeForces 235C Cyclical Quest
- CodeForces 235C(后缀自动机)
- CodeForces 235C Cyclical Quest 后缀自动机
- Codeforces 235C Cyclical Quest 后缀自动机
- Codeforces 427D Match & Catch 后缀自动机
- Codeforces 427D Match & Catch 后缀自动机 或 后缀数组
- 后缀自动机
- 后缀自动机
- 后缀自动机
- 后缀自动机
- cf Gym
- Java中的Math类和日期类详解
- Android对象序列化
- 外包管理随想一---抓大、放小、管细
- ENVI拼接图片
- codeforces 802I 后缀自动机
- 关于Java WEB项目中中文乱码的解决方法
- selenium爬虫需要注意检测页面加载和内容加载进度
- ubuntu下安装matlab教程
- composer手动安装
- HDU 4734F(x)
- 《华为机试在线训练》之简单密码
- selenium 的显示等待与隐式等待
- 面试相关