跳到正文

个人记录

8.21-401-下午 总结

tiko_vency约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月21日
收录
2026年8月22日
更新
2026年11月13日
篇幅
约 5 分钟

版本

  1. v1当前

P10468 兔子与兔子

就是将字符串用整数处理,我们可以把它想成一个PP(通常为131131)进制的数,用hh数组遍历前缀,即hi=hi−1∗P+(si−′a′)h_i=h_{i-1}*P+(s_i-'a'),如果越界要取模,我们可以用unsigned long longunsigned\ long\ long,这样就能自动取模

我们可以用pp数组找PiP^i是多少

之后我们判断一个字符截取的两个部分是否相等,判断就是让他们变成两个数,直接用hr−hl−1∗pr−l+1h_r-h_{l-1}*p_{r-l+1},即前缀和相减得区间和,乘pr−l+1p_{r-l+1}让他们同位相减

代码:

C++
#include<bits/stdc++.h>
#define int unsigned long long
using namespace std;
const int N=1e6+10,P=131;
int n,l1,r1,l2,r2,h[N],p[N];
string s;
int get(int l,int r){
	return h[r]-h[l-1]*p[r-l+1];
}
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>s>>n;
	s=' '+s,p[0]=1;
	for(int i=1;i<s.size();i++)
		h[i]=h[i-1]*P+(s[i]-97),p[i]=p[i-1]*P;
	for(int i=1;i<=n;i++){
		cin>>l1>>r1>>l2>>r2;
		cout<<(get(l1,r1)==get(l2,r2)?"Yes\n":"No\n");
	}
	return 0;
}

P10479 匹配统计

给定字符串a,ba,b,qq次询问,每次询问给出一个数xx,求所有aa的后缀子串中,满足:“与bb的匹配长度恰好为xx”的字符串个数。其中“匹配长度”指两个字符串最长的公共前缀子串,如abcabc与abxabx的匹配长度就为22

代码:

C++
#include<bits/stdc++.h>
#define ull unsigned long long
using namespace std;
const int N=2e5+10,P=131;
int n,m,q,x,l,r,mid,ans[N];
ull ha[N],hb[N],p[N],tmpa,tmpb;
string a,b;
ull geta(int l,int r){
	return ha[r]-ha[l-1]*p[r-l+1];
}
ull getb(int l,int r){
	return hb[r]-hb[l-1]*p[r-l+1];
}
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>n>>m>>q>>a>>b;
	a=' '+a,b=' '+b,p[0]=1;
	for(int i=1;i<=n;i++)
		ha[i]=ha[i-1]*P+a[i];
	for(int i=1;i<=m;i++)
		hb[i]=hb[i-1]*P+b[i];
	for(int i=1;i<=2e5;i++)
		p[i]=p[i-1]*P;
	for(int i=1;i<=n;i++){
		l=-1,r=max(n-i+1,m)+1;
		while(l+1<r){
			mid=(l+r)/2,tmpa=geta(i,i+mid-1),tmpb=getb(1,mid);
			if(tmpa==tmpb)
				l=mid;
			else
				r=mid;
		}
		ans[(l!=-1?l:0)]++;
	}
	for(int i=1;i<=q;i++){
		cin>>x;
		cout<<ans[x]<<"\n";
	}
	return 0;
}

U577114 M形字符串

这就是一个哈希,但是要平均分成22份,然后2个字符串一个从前向后,一个从后向前,找多少个前/后字符串相等,相等计数的ansans就加一

代码:

C++
#include<bits/stdc++.h>
#define int unsigned long long
using namespace std;
const int N=2e5+10,P=131;
int n,h[N][2],p[N],ans;
string s;
int get(bool f,int l,int r){
	return h[r][f]-h[l-1][f]*p[r-l+1];
}
int get2(bool f,int l,int r){
	return h[l][f]-h[r+1][f]*p[r-l+1];
}
bool check(int l,int r){
	return get(0,l,r)==get2(1,l,r);
}
signed main(){
	ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
	cin>>s;
	s=" "+s,n=s.size(),p[0]=1;
	for(int i=1;i<=n;i++)
		p[i]=p[i-1]*P,h[i][0]=h[i-1][0]*P+s[i];
	for(int i=n;i>0;i--)
		h[i][1]=h[i+1][1]*P+s[i];
	for(int i=1;i<=n;i++)
		if(check(1,i)&&check(1,(i+1)/2))
			ans++;
	cout<<ans;
	return 0;
}
原文