[ABC441E] A > B substring 新解法

· · 题解

::::info[说明]

赛时想的奇葩写法,非正解,想要学习正解的同学请看其他的题解。

::::

前置芝士:

  1. 前缀和
  2. pb_ds 库中的 tree 数据结构,不会的建议先学习一下

容易想到暴力算法,先前缀和一遍,再枚举左右端点,如果可行就答案加一。时间复杂度为 O(n^2),无法通过本题。

::::success[代码]{open}

for(int i=1;i<=n;i++){
    prea[i]=prea[i-1],preb[i]=preb[i-1];//prea,preb是前缀和数组
    if(s[i]=='A') prea[i]++;
    else if(s[i]=='B') preb[i]++;
   //注意到单独的 A 也是可行的,所以顺序得要这样
     for(int j=1;j<=i;j++){
         if(prea[i]-prea[j-1]>preb[i]-preb[j-1]){
             ans++;
         }
     }
}

::::

设 prea_i 表示前 i 个字符中有多少个 A,preb_i 表示前 i 个字符中有多少个 B。

注意到不等式

prea_i - prea_{j-1} > preb_i - preb_{j-1}

等价于

prea_i - preb_i > prea_{j-1} - preb_{j-1}

所以我们维护一个集合,第 i 个元素是 prea_i - preb_i,让其保持有序,不难想到用 STL 中的 map。遍历数组,设当前遍历到 i,让答案加上集合中小于 prea_i - preb_i 的元素个数,这个可以用二分查找。

可是 map 查找小于某个数的元素个数的效率是 O(n) 的,因为它在内存中不是连续存储的,所以它是不能随机访问。

难道就没有办法了吗,难道就只能用逆序对的方法了吗?

不难想到 GCC 为 OIer 们提供了一种良心的东西———— pb_ds。它可以在 O(\log n) 的时间复杂度查找集合内小于某个数的元素个数。

可以这样定义它:

tree<long long,
 null_type,
less_equal<long long>,
rb_tree_tag, tree_order_statistics_node_update> ms;

以及使用内置的 order_of_key 函数。

知道了这些,代码就很好写了。

::::success[代码]

//  Gavinzhou's code
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds; 
using namespace std;
//#define LOCAL
#define in freopen("xx.in","r",stdin)
#define out freopen("xx.out","w",stdout)
#define int long long
#define endl '\n'
#define FastIO std::ios::sync_with_stdio(false);cin.tie(0);
#define fi first
#define se second
#define dis(x1,y1,x2,y2) (sqrt(Abs(x1-x2)*Abs(x1-x2)+Abs(y1-y2)*Abs(y1-y2)))
using PII=pair<int,int>;
/*--------------------定义变量,函数---------------------------*/
const int N=5e5+5;
int n;
string s;
int prea[N],preb[N];
/*-----------------------解决函数--------------------------*/
void solve(){
    cin>>n>>s;
    s=' '+s;
    int ans=0;
tree<long long, null_type, less_equal<long long>, rb_tree_tag, tree_order_statistics_node_update> ms;
    ms.insert(0);
    for(int i=1;i<=n;i++){
        prea[i]=prea[i-1],preb[i]=preb[i-1];
        if(s[i]=='A') prea[i]++;
        else if(s[i]=='B') preb[i]++;
        // for(int j=1;j<=i;j++){
        //     if(prea[i]-preb[i]>prea[j-1]-preb[j-1]){
        //         ans++;
        //     }
        // }
        ans+=ms.order_of_key(prea[i]-preb[i]);
        ms.insert(prea[i]-preb[i]);
    }
    cout<<ans;
}
void clear(){
}
/*------------------------------------------------------*/
signed main(){
  FastIO
#ifdef LOCAL
    in;
    out;
#endif
  int t;
  t=1;
  while(t--){
    solve();
  }
  return 0;
}

::::

完美通过