--- 这里是 cjiaw 的小窝(●'◡'●) ---

正在玩命加载中......

CF_2145_C. Monocarp's String

题目链接:https://codeforces.com/contest/2145/problem/C


题目大意:

长度为 n 的字符串 s ,由字母‘a’‘b’组成,删除一些连续(可能为零)的字母,从而使结果字符串中的字母‘a’‘b’的数量相等

求:从字符串 s 中删除的连续字母的最小数量


思路:

把a看成1,b看成-1,记录前缀和A,

根据前缀和原理,要让 a 与 b 的数量相等,需要 A[n] = A[r] - A[l] = 删去的字母

所以我们要找满足 A[r] - A[l] = A[n] 的区间,且区间长度 r - l 最小;

变形一下,得 A[r] - A[n] = A[l] ,我们只需遍历 r ,记录最近的 l 下标即可

注意 A[i] 的区间在 [ -n , n ] 中,在记录位置的时候加上 N ,保证下标不会越界负数


代码:

 

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<bitset>
#include<tuple>
#define inf 72340172838076673
#define int long long
#define endl '\n'
#define F first
#define S second
#define  mst(a,x) memset(a,x,sizeof (a))
using namespace std;
typedef pair<int, int> pii;

const int N = 200086, mod = 998244353;

int n, m;
char s[N];
int a[N];
int sum[N * 2];

void solve() {

    cin >> n >> s + 1;
    for (int i = 1; i <= n; i++) {
        if (s[i] == 'a') a[i] = a[i - 1] + 1;
        else a[i] = a[i - 1] - 1;
    }
    
    if (a[n] == 0) cout << 0 << endl;
    else {
        int res = inf;
        sum[N] = 0;
        for (int i = 1; i <= n; i++) {
            //如果出现过,即a[l]=a[r]-a[n]
            if (sum[a[i] - a[n] + N] != -1) res = min(res, i - sum[a[i] - a[n] + N]);
            sum[a[i] + N] = i;//标记最近的该前缀和的位置
        }
        if (res < n) cout << res << endl;
        else cout << -1 << endl;
    }
    
    for (int i = N - n - 1; i <= N + n + 1; i++) sum[i] = -1;
    
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    
    mst(sum, -1);
    int T = 1;
    cin >> T;
    while (T--) solve();
    
    return 0;
}

 

posted @ 2025-10-07 11:46  wwjjw  阅读(55)  评论(3)    收藏  举报