B4153 题解 & 梦开始的地方

· · 题解

说句闲话

时隔两年,考场选手来补题了,这里是我 OI 梦开始的地方。

Subtask 1

### Subtask 2 特殊性质,发现每个子串都是合法的,输出 $\frac{1}{2}n(n+1)$,期望得分 $10$。 ### Subtack 3 & 4 考虑树状数组,只枚举一个端点 $l$,快速计算有多少个 $r$ 满足 $sum_r>sum_{l-1}$。时间复杂度 $O(n\log n)$,期望得分 $60$。 ```cpp #include<bits/stdc++.h> #define int long long #define lowbit(x) (x&(-x)) #define N 10000005 using namespace std; int n,ans,sum[N],c[N*2]; char ch; void update(int x,int y) { while(x<=20000000) c[x]+=y,x+=lowbit(x); return; } int query(int x) { int res=0; while(x) res+=c[x],x-=lowbit(x); return res; } signed main() { ios::sync_with_stdio(0); cin>>n; for(int i=1;i<=n;i++) cin>>ch,sum[i]=sum[i-1]+((ch=='0')?-1:1); for(int i=0;i<=n;i++) sum[i]+=10000000; for(int i=0;i<=n;i++) update(sum[i],1); for(int i=1;i<=n;i++) { ans+=query(20000000)-query(sum[i-1]); update(sum[i-1],-1); } cout<<ans; return 0; } ``` ### Subtask 5 发现字符串中只有 $0$ 和 $1$,因此 $sum_i$ 和 $sum_{i-1}$ 的差不超过 $1$。枚举端点 $r$,同时维护一个变量 $cnt$ 和数组 $tot$,分别表示满足 $l<r$ 且 $sum_r>sum_{l-1}$ 的 $l$ 的个数和前缀和小于 $i$ 的个数。 如果 $s_i=0$,那么 $sum_i=sum_{i-1}-1$,则原来 $sum_{i-1}>sum_{i-1}-1$,而现在不满足了,所以 $cnt$ 要减去 $tot_{sum_{i-1}-1}$。 如果 $s_i=1$,那么 $sum_i=sum_{i-1}+1$,则原来 $sum_{i-1}\le sum_{i-1}$,现在满足 $sum_{i}>sum_{i-1}$,因此 $cnt$ 要加上 $tot_{sum_{i-1}}$。 注意数组下标不能为负,需要加上一个偏移量 $10^7$。然后就做完了。 ```cpp #include<bits/stdc++.h> #define N 10000005 using namespace std; int n,cnt,sum,tot[N*2]; char ch; long long ans; int read() { int x=0; char c=getchar(); while(c<'0'||c>'9') c=getchar(); while(c>='0'&&c<='9') x=x*10+c-48,c=getchar(); return x; } int main() { n=read(); tot[10000000]=1; for(int i=1;i<=n;i++) { ch=getchar(); if(ch=='0') cnt-=tot[sum-1+10000000],sum--; else cnt+=tot[sum+10000000],sum++; tot[sum+10000000]++; ans+=cnt; } cout<<ans; return 0; } ```