跳到正文

题解

题解:AT_abc441_e AT_abc441_e [ABC441E] A > B substring

月落彼岸的鲸约 3 分钟
原文

这是 2026年1月19日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年1月19日
收录
2026年1月19日
更新
2026年11月14日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

题解:AT_abc441_e AT_abc441_e [ABC441E] A > B substring

题目传送门 luogu

题目传送门 AT

思路:

首先看题,发现 CC 的位置对答案没影响,所以只考虑 AA 和 BB。

然后看,要子串中 AA 的数量大于 BB,所以我们姑且将遍历 AA 时加 11,遍历到 BB 时减 11。每便利到一个就加上前面的小于他的,由此写出了暴力。

C++
#include<bits/stdc++.h>
using namespace std;
long long n,ans,cnt,tr[2000005];//做了偏移,使原本减b时负的变成正的
string s;
int main(){
  ios::sync_with_stdio(0);
  cin.tie(0) ,cout.tie(0);
  cin>>n>>s;
  s=" "+s;
  tr[n]=1; 
  cnt=n;
  for(int i=1;i<=n;i++){
  	cnt=cnt+(s[i]=='A')-(s[i]=='B');
      tr[cnt]++;
      for(int j=0;j<cnt;j++) ans+=tr[j];
  } 
  cout<<ans;


return 0;
}

发现要累加 trtr 这个数组,就想到用树状数组优化。

C++
#include<bits/stdc++.h>
using namespace std;
long long n,ans,cnt,tr[2000005];
string s;
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0) ,cout.tie(0);
	cin>>n>>s;
	s=" "+s;
	for(int i=n+1;i<2*n+1;i=i+(i&(-i))) tr[i]++;
	for(int i=1;i<=n;i++){
		cnt=cnt+(s[i]=='A')-(s[i]=='B');
		for(int i=cnt+n;i>0;i=i-(i&(-i))) ans+=tr[i];
		for(int i=cnt+n+1;i<2*n+1;i=i+(i&(-i))) tr[i]++;
	} 
	cout<<ans;


return 0;
}

时间复杂度是 Θ(n log n)\Theta(n \ log \ n),再想一下优化。 看暴力代码,每次 ansans 加的是 ∑i=0cnttri\sum_{i = 0}^{cnt} tr_i,cntcnt 每次变一个,所以我们只处理每次 cntcnt 变化后的这个位置即可。

C++
#include<bits/stdc++.h>
using namespace std;
long long n,ans,cnt,tr[2000005],o=0;//做了偏移,使原本减b时负的变成正的
string s;
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0) ,cout.tie(0);
	cin>>n>>s;
	s=" "+s;
	tr[n]=1,cnt=n; 
	for(int i=1;i<=n;i++){
		if(s[i]=='A'){
			cnt++;
			o+=tr[cnt-1];
		} else if(s[i]=='B'){
			cnt--;
			o-=tr[cnt];
		}
	    tr[cnt]++;
	    ans+=o;
	} 
	cout<<ans;


return 0;
}

时间复杂度是 Θ(n)\Theta(n),完美收工。

求过。