题解:CF2072B Having Been a Treasurer in the Past, I Help Goblins Deceive

· · 题解

题意简述

重新排列字符串 s,使得 s 中子序列 -_- 的个数最多,并输出最多的个数。

AC思路

考虑贪心,把 s 变成形如

\texttt{--} \dots \texttt{--\_\_} \dots \texttt{\_\_--} \dots \texttt{--}

的形式(先是若干个 -,再是若干个 _,最后是若干个 -)。

那么这个字符串的 -_- 子序列个数为:第一段 - 个数 \times 中间 _ 的个数 \times 第二段 - 个数。
其中 _ 的个数是确定的,就得让第一段 - 个数 \times 第二段 - 个数最大,那就让两段的个数尽量接近。设 - 的个数为 cnt,那么两段长度分别为 \lfloor \frac{cnt}{2} \rfloor 和 cnt - \lfloor \frac{cnt}{2} \rfloor。

AC代码

#include <bits/stdc++.h>
using namespace std;
int t, n, cnt;
string s;
int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> t;
    while (t --){
        cin >> n >> s;
        cnt = 0; // 统计`-`的个数。
        for (int i = 0; i < n; ++ i){
            cnt += (s[i] == '-');
        }
        cout << (cnt / 2) * 1ll * (cnt - cnt / 2) * (n - cnt) << '\n';
    }
    return 0;
}

最后再说一句:不开 long long 见祖宗!