【洛谷 P5410】【模板】扩展 KMP / Z-algorithm

传送门

z i z_i 表示 l c p ( s [ i . . . . n ] , s [ 1.... n ] ) \mathit{lcp}(s[i....n],s[1....n])

只用考虑对一个串处理 n x t nxt ,另一个匹配是一样
假设当前在 i i ,所有 j + z j 1 ( j < i ) j+z_j-1(j<i) 中最大值为 r r ,这最大的 j j 设为 l l
如果 r < i r<i ,继续暴力匹配即可
否则设 k = i l + 1 k=i-l+1 ,显然 s [ i . . . r ] , s [ k . . . k + r i ] s[i...r],s[k...k+r-i] 是一样的
i + z k p , z i = z k i+z_{k}\le p,z_i=z_k
否则 z i = r i + 1 z_i=r-i+1, 暴力拓展即可

复杂度 O ( n ) O(n)

#include<bits/stdc++.h>
using namespace std;
#define cs const
#define re register
#define pb push_back
#define pii pair<int,int>
#define ll long long
#define y1 shinkle
#define fi first
#define se second
#define bg begin
cs int RLEN=1<<20|1;
inline char gc(){
    static char ibuf[RLEN],*ib,*ob;
    (ib==ob)&&(ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
    return (ib==ob)?EOF:*ib++;
}
inline int read(){
    char ch=gc();
    int res=0;bool f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
inline ll readll(){
    char ch=gc();
    ll res=0;bool f=1;
    while(!isdigit(ch))f^=ch=='-',ch=gc();
    while(isdigit(ch))res=(res+(res<<2)<<1)+(ch^48),ch=gc();
    return f?res:-res;
}
inline int readstring(char *s){
	int top=0;char ch=gc();
	while(isspace(ch))ch=gc();
	while(!isspace(ch)&&ch!=EOF)s[++top]=ch,ch=gc();
	s[top+1]='\0';return top;
}
template<typename tp>inline void chemx(tp &a,tp b){a=max(a,b);}
template<typename tp>inline void chemn(tp &a,tp b){a=min(a,b);}
cs int N=20000007;
char s[N],t[N];
int n,m,z[N],anc[N];
inline void init_z(){
	z[1]=n;
	for(int i=2,l=0,r=0;i<=n;i++){
		if(i<=r)z[i]=min(z[i-l+1],r-i+1);
		while(i+z[i]<=n&&s[i+z[i]]==s[z[i]+1])z[i]++;
		if(i+z[i]-1>r)l=i,r=z[i]+i-1;
	}
}
inline void exkmp(){
	init_z();
	for(int i=1,l=0,r=0;i<=m;i++){
		if(i<=r)anc[i]=min(z[i-l+1],r-i+1);
		while(i+anc[i]<=m&&t[i+anc[i]]==s[anc[i]+1])anc[i]++;
		if(i+anc[i]-1>r)l=i,r=anc[i]+i-1;
	}
}
int main(){
	#ifdef Stargazer
	freopen("lx.in","r",stdin);
	#endif
	m=readstring(t),n=readstring(s);
	exkmp();
	ll res=0;
	for(int i=1;i<=n;i++)res^=(ll)i*(z[i]+1);
	cout<<res<<'\n';
	res=0;
	for(int i=1;i<=m;i++)res^=(ll)i*(anc[i]+1);
	cout<<res<<'\n';return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42555009/article/details/105825746