CF1927A Make it White solution

· · 个人记录

形式化题意:给定一串长度为 n 的字符串 s, s 中只包含 B 和 W ,你可以选择它的一段子串,将该子串内的所有元素染成 W 。要使该字符串全部染成 W ,求选择的子串的最小长度。

为了保证字符串全部染成 W ,那就只能排除字符串两边的 W ,所以就分别从两头往中间扫,直到找到一个 B 就退出。容易证明,这一定是最优解。

时间复杂度 O(n)。

code:

#include<iostream>
#include<cstdio>
#include<bitset>
using namespace std;
const int MAXN=15;
int T;
int n;
bitset <MAXN> s;
int ans;
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>T;
    char c;
    int ck;
    while(T--)
    {
        cin>>n;
        for(int i=1;i<=n;++i)
        {
            cin>>c;
            s[i]=(c=='W' ? 1 : 0);
        }
        ck=1;
        ans=n;
        while(s[ck]) ++ck,--ans;
        ck=n;
        while(s[ck]) --ck,--ans;
        cout<<ans<<'\n';
    }
    return 0;
}