说句闲话
时隔两年,考场选手来补题了,这里是我 OI 梦开始的地方。
Subtask 1
的贡献为 , 的贡献为 。做一遍前缀和,记为 。枚举子串的端点,计算这个子串的贡献 是否大于 。时间复杂度为 ,期望得分 。
Subtask 2
特殊性质,发现每个子串都是合法的,输出 ,期望得分 。
Subtack 3 & 4
考虑树状数组,只枚举一个端点 ,快速计算有多少个 满足 。时间复杂度 ,期望得分 。
#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
发现字符串中只有 和 ,因此 和 的差不超过 。枚举端点 ,同时维护一个变量 和数组 ,分别表示满足 且 的 的个数和前缀和小于 的个数。
如果 ,那么 ,则原来 ,而现在不满足了,所以 要减去 。
如果 ,那么 ,则原来 ,现在满足 ,因此 要加上 。
注意数组下标不能为负,需要加上一个偏移量 。然后就做完了。
#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;
}