跳到正文

题解

题解:P9576 「TAOI-2」Ciallo~(∠・ω< )⌒★

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

文章信息

收录
2026年2月23日
更新
2026年2月23日
篇幅
约 5 分钟
题目
P9576

版本

  1. v1当前

哈希 + 树状数组。

首先考虑将答案分两类:tt 为 ss 的子串、tt 为 ss 的两个不相邻子串拼接。

对于第一种,删掉的区间肯定与匹配部分不交,枚举左端点,哈希判子串,小学数学计算即可。

对于第二种,如果左、右端点确定了,那么删掉的区间肯定在中间,长度也确定了。

考虑计算两个数组 a,ba,b。aia_i 表示 s[i,∣s∣]s[i,|s|] 和 tt 的 LCP 长度,bib_i 表示 s[1,i]s[1,i] 和 tt 的 LCS 长度。这可以 O(log⁡∣t∣)\mathcal O(\log|t|) 哈希二分求出。

先思考 O(n2)\mathcal O(n^2) 的做法,枚举左、右端点 i,ji,j,它们对答案有贡献,当且仅当

{j−i+1>∣t∣ai+bj≥∣t∣\begin{cases} j-i+1>|t|\\ a_i+b_j\ge|t| \end{cases}

第一行:它必须是被删掉区间分开的。
第二行:它必须能被拼出来。
它的贡献是 ai+bj−∣t∣+1a_i+b_j-|t|+1。

将不等式组移项

{i<j−∣t∣+1ai≥∣t∣−bj\begin{cases} i<j-|t|+1\\ a_i\ge|t|-b_j \end{cases}

然后就变成二位偏序了。注意到 ai+bj−∣t∣+1=(ai−∣t∣+1)+bja_i+b_j-|t|+1=(a_i-|t|+1)+b_j,双指针将 aia_i 放到树状数组里,两个树状数组记录 aia_i 的数量以及 ai−∣t∣+1a_i-|t|+1 之和即可。

总时间复杂度 O(∣s∣log⁡∣t∣)\mathcal O(|s|\log|t|),如有不懂见代码。

AC 代码
C++
#include <bits/stdc++.h>
#define fi first
#define se second
#define mid ((l+r)>>1)
#define bmid ((l+r+1)>>1)
#define pb push_back
#define eb emplace_back
using namespace std;
using ll= long long;
using ull= unsigned long long;
#ifndef ONLINE_JUDGE
template <typename tp>
void _debug(const tp& t) {cerr<<t<<'\n';}
template <typename tp,typename... args>
void _debug(const tp& t, const args&... rest) {cerr<<t<<' ';_debug(rest...);}
#define debug(...) _debug(#__VA_ARGS__ " =", __VA_ARGS__)
#else
#define debug(...) 0
#endif
const int N=400005,B=131,H=N<<2,inf=1000000000,mod=1000000007;
void hsh(const string& s,ull h[]) {
	const int n=s.size()-1;
	h[0]=0;
	for(int i=1;i<=n;i++)
		h[i]=h[i-1]*B+s[i];
}
ull pw[N];
ull sh(ull h[],int l,int r) {
	return l>r?0:h[r]-h[l-1]*pw[r-l+1];
}
ull h1[N],h2[N];
string s,t;
int n,m,a[N],b[N];
struct bit {
	ll c[N];
	void upd(int i,ll x) { i++;
		for(;i<=m+1;i+=i&-i)
			c[i]+=x;
	}
	ll query(int i) { i++;
		ll ret=0;
		for(;i>0;i-=i&-i)
			ret+=c[i];
		return ret;
	}
} b1,b2;
inline ll c2(ll x) {
	return x*(x-1)>>1;
}
int main() {
	for(int i=pw[0]=1;i<N;i++)
		pw[i]=pw[i-1]*B;
	cin.tie(nullptr)->sync_with_stdio(false);
	cin>>s>>t;
	n=s.size(),m=t.size();
	s="@"+s,t="@"+t;
	hsh(s,h1);
	hsh(t,h2);
	for(int i=1;i<=n;i++) if(s[i]==t[1]) {
		int l=1,r=min(m,n-i+1);
		while(l<r) {
			if(sh(h1,i,i+bmid-1)==sh(h2,1,bmid)) l=bmid;
			else r=bmid-1;
		}
		a[i]=l;
	}
	for(int i=1;i<=n;i++) if(s[i]==t[m]) {
		int l=1,r=min(m,i);
		while(l<r) {
			if(sh(h1,i-bmid+1,i)==sh(h2,m-bmid+1,m)) l=bmid;
			else r=bmid-1;
		}
		b[i]=l;
	}
	ll ans=0;
	int p=1;
	for(int i=1;i<=n;i++) {
		while(p<=i-m) {
			b1.upd(a[p],+1);
			b2.upd(a[p],+a[p]-m+1);
			p++;
		}
		const ll cb1=b1.query(m)-b1.query(m-b[i]-1);
		const ll cb2=b2.query(m)-b2.query(m-b[i]-1);
		ans+=cb2+cb1*b[i];
	}
	for(int i=1;i+m-1<=n;i++)
		if(sh(h1,i,i+m-1)==sh(h2,1,m))
			ans+=c2(i-1)+c2(n-(i+m-1));
	cout<<ans;
	return 0;
}
原文