题解:P9576 「TAOI-2」Ciallo~(∠・ω< )⌒★
哈希 + 树状数组。
首先考虑将答案分两类:
对于第一种,删掉的区间肯定与匹配部分不交,枚举左端点,哈希判子串,小学数学计算即可。
对于第二种,如果左、右端点确定了,那么删掉的区间肯定在中间,长度也确定了。
考虑计算两个数组
先思考
第一行:它必须是被删掉区间分开的。\
第二行:它必须能被拼出来。\
它的贡献是
将不等式组移项
然后就变成二位偏序了。注意到
总时间复杂度
#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;
}
:::