• 洛谷 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;
    }
    
  • 相关阅读:
    测试是否有必要看开发代码?如何能看懂?
    【LeetCode】111. 二叉树的最小深度(BFS 解题套路框架,要会默写)
    【LeetCode】112. 路径总和
    【测试开发】知识点配置 Nginx 解决多端口访问
    【测试开发】知识点使用EasyExcel,实现excel导出和导入
    p5 随机圆连接背景和代码树
    angular技巧
    javascript原生技巧篇
    MybatisPlus
    安装 jupyter notebook
  • 原文地址:https://www.cnblogs.com/BakaCirno/p/12670814.html
Copyright © 2020-2023  润新知