zoukankan      html  css  js  c++  java
  • 洛谷 P5341 [TJOI2019]甲苯先生和大中锋的字符串【SAM】

    传送门
    拿到一个串之后,先对它建立 SAM,然后统计每个节点的 (endpos) 值,就是每个节点所代表的子串所出现的次数,如果这个 (endpos[x]=k),那么长为 (len[fa[x]]+1,...,len[x]) 的子串都合法,用差分的方式区间加,然后最后统计答案就是了。

    #include <bits/stdc++.h>
    using namespace std;
    typedef long long LL;
    const int N=1e5+10;
    int n,k,ans,cnt[N];
    char s[N];
    struct SuffixAutoMachine{
    	int tot,last,ch[N*2][26],fa[N*2],len[N*2],epos[N*2];
    	int newnode(int id){fa[++tot]=fa[id];len[tot]=len[id];memcpy(ch[tot],ch[id],sizeof(ch[tot]));return tot;}
    	int head[N*2],to[N*2],nxt[N*2],total;
    	void add(int u,int v){to[++total]=v;nxt[total]=head[u];head[u]=total;}
    	void insert(int c){
    		int p=last,np=last=newnode(0);
    		len[np]=len[p]+1;epos[np]=1;
    		for(;p&&!ch[p][c];p=fa[p]) ch[p][c]=np;
    		if(!p) {fa[np]=1;return;}
    		int q=ch[p][c];
    		if(len[q]==len[p]+1) {fa[np]=q;return;}
    		int nq=newnode(q);len[nq]=len[p]+1;
    		fa[q]=fa[np]=nq;
    		for(;p&&ch[p][c]==q;p=fa[p]) ch[p][c]=nq;
    	}
    	void dfs(int u){
    		for(int i=head[u];i;i=nxt[i]) dfs(to[i]),epos[u]+=epos[to[i]];
    		if(epos[u]==k) cnt[len[fa[u]]+1]++,cnt[len[u]+1]--;
    	}
    	void init(){
    		tot=last=total=0;
    		memset(head,0,sizeof(head));
    		memset(epos,0,sizeof(epos));
    		last=newnode(0);
    		for(int i=1;i<=n;i++) insert(s[i]-'a');
    		for(int i=2;i<=tot;i++) add(fa[i],i);
    		dfs(1);
    	}
    }sam;
    
    void solve(){
    	memset(cnt,0,sizeof(cnt));
    	scanf("%s%d",s+1,&k);
    	n=strlen(s+1);
    	ans=0;
    	sam.init();
    	for(int i=1;i<=n;i++){
    		cnt[i]+=cnt[i-1];
    		if(cnt[i]>=cnt[ans]) ans=i;
    	}
    	printf("%d
    ",cnt[ans]>0?ans:-1);
    }
    
    int main(){
    	int T;scanf("%d",&T);
    	while(T--) solve();
    	return 0;
    }
    
  • 相关阅读:
    关于ACID,BASE和CAP定理的探究
    2020年10月3日——武汉,成都,南京房价揭秘
    程序员如何选择自己的保险
    Yarn系列(一)——Yarn整体介绍
    利用媒体查询实现响应式布局
    移动端web布局:适配
    scss在编辑器中保存自动编译css插件及安装
    移动端web布局:像素与成像的基本原理
    微信小程序:路由
    自定义vue指令
  • 原文地址:https://www.cnblogs.com/BakaCirno/p/12670814.html
Copyright © 2011-2022 走看看