Title

CF1913B Swap and Delete 题解

解题思路

我们将题意转化一下:

  • s 的反转后的字符串的一个最长前缀,使其满足可以通过 s 得到。

显然,交换不会改变每种字符的数量。那么,我们先把 s 求出其中 0 的数量 s0,和 1 的数量 s1,然后将 s 每位反转(01),然后从第一位开始,记录此时的 0 的数量 t01 的数量 t1,如果这个时候有 t0=s0t1=s1,那么直接输出 ni 即可;如果 t0>s0t1>s1,那么输出 ni+1

AC 代码

#include<math.h>
#include<time.h>
#include<stdio.h>
#include<algorithm>
#define ll long long
#include<cstring>
#define N 200005
char s[N];
inline void work(){
    scanf("%s",s+1);
    int n=strlen(s+1);
    int s0=0,s1=0;
    for(register int i=1;i<=n;++i){
        if(s[i]=='0') ++s0;
        else ++s1;
    }int t1=0,t0=0;
    for(register int i=1;i<=n;++i){
        if(s[i]=='0') ++t1;
        else ++t0;
        if(t1==s1&&t0==s0){
            printf("%d\n",n-i);
            return;
        }else if(t1>s1||t0>s0){
            printf("%d\n",n-i+1);
            return;
        }
    }
}signed main(){
    srand(114514);
    srand(rand());
    srand(time(0));
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    int T;scanf("%d",&T);
    while(T--) work();
    return 0;
}
posted @   UncleSam_Died  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示