题解:P14563 跳跃
先考虑带特殊性质
特殊性质
考虑如何计算第二个数,设
然后设
然后倍增跳即可。
现在考虑去掉特殊性质
那么把每段中的
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pii pair<ll,ll>
#define dgd priority_queue<int>
#define xgd priority_queue<int,vector<int>,greater<int> >
#define fi first
#define se second
#define pbk push_back
#define all(_c) _c.begin(),_c.end()
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define per(i,a,b) for(int i=(a);i>=(b);i--)
#define nl cout << "\n"
const int INF=1e9;
const ll Inf=4e18;
const int abc=26;
const double pi=3.1415926;
int read(){
int x=0,f=1;char c=getchar();
while(c<'0'||c>'9'){if(c=='-') f=-1;c=getchar();}
while(c>='0'&&c<='9'){x=x*10+c-48;c=getchar();}
return x*f;
}
const int maxn=5e5+10;
ll c,n,q,k,t,a[maxn],b[maxn];
string s;
ll C[maxn];
struct blk{
ll l,r,x;
}B[maxn];
ll top,lst=1;
ll N,P[maxn],S[maxn];
ll Top,nxt[maxn][20],W[maxn],id[maxn];
void solve(){
cin >> c >> n >> q >> k >> t >> s;
rep(i,1,n) C[i]='1'-s[i-1];
rep(i,1,n) S[i]=S[i-1]+C[i];
rep(i,1,n){
if(C[i]==0){
if(lst<i){
top++;
B[top].l=lst;B[top].r=i-1;B[top].x=B[top-1].x+(B[top].r-B[top].l+1)/k;//注意这里的前缀和
rep(j,1,(B[top].r-B[top].l+1)%k) P[++N]=1;//维护保留L mod k 的黑块的剩余序列
}
lst=i+1;
P[++N]=C[i];
id[i]=N;
}
}
if(lst<=n){
top++;
B[top].l=lst;B[top].r=n;B[top].x=B[top-1].x+(B[top].r-B[top].l+1)/k;
rep(j,1,(B[top].r-B[top].l+1)%k) P[++N]=1;
}
rep(i,1,N+1){
rep(j,0,19) nxt[i][j]=N+1
}
rep(i,1,N){
if(P[i]==0) W[++Top]=i;
}
rep(i,1,Top-1){
ll l=i+1,r=Top;
while(l<=r){
ll mid=(l+r)>>1;
if(W[mid]-W[i]<=k) nxt[W[i]][0]=W[mid],l=mid+1;
else r=mid-1;
}
}//nxt加速跳
rep(i,1,19){
rep(j,1,N){
nxt[j][i]=nxt[nxt[j][i-1]][i-1];
}
}
rep(i,1,q){
cin >> a[i] >> b[i];
if(b[i]<a[i]) swap(a[i],b[i]);//题目里有ai>bi的情况,要换回来
}
rep(i,1,q){
int L=1,R=top,ans1=0,ans2=0,ans=0;
if(S[b[i]]-S[a[i]-1]==0){//中间没有块,那还说啥了
ans=0;
}else{
while(L<=R){//二分[ai,bi]中完整的黑色块,这些每个会对ans造成L/k的贡献
int mid=(L+R)>>1;
if(B[mid].l>=a[i]) ans1=mid,R=mid-1;
else L=mid+1;
}
L=1;R=top;
while(L<=R){
int mid=(L+R)>>1;
if(B[mid].r<=b[i]) ans2=mid,L=mid+1;
else R=mid-1;
}
ans=B[ans2].x-B[ans1-1].x;//用前面算的前缀和算
}
cout << ans << " ";
if(t==1){//加速跳
ll cnt=0;
a[i]=id[a[i]];b[i]=id[b[i]];
per(j,19,0){
if(nxt[a[i]][j]<b[i]) a[i]=nxt[a[i]][j],cnt+=(1<<j);
}
cout << cnt+ans+1;//记得加上ans,黑色块跳的也算,思考一下这里为什么要+1(和倍增LCA深度相同后跳的原理一样)
}
cout << "\n";
}
nl;
return;
}
int main(){
//ios::sync_with_stdio(false);
//cout.tie(0),cin.tie(0);
int t=1;
//cin >> t;
while(t--) solve();
return 0;
}