zoukankan      html  css  js  c++  java
  • Crazy Binary String(前缀和)(2019牛客暑期多校训练营(第三场))

    示例:

    输入:

    8
    01001001

    输出:4 6

    题意:一段长度为n且只有 ‘0’ 和 ‘1’ 的字符串,求子串中 ‘0’ 和 ‘1’ 数目相等和子序列中 ‘0’ 和 ‘1’ 数目相等的最大长度。

    思路:子序列的最大长度为 ‘0’ 和 ‘1’ 的个数中最小的两倍;

    求字串的最大长度就用前缀和,将 ‘1’ 的价值设为1,‘0’ 的价值设为-1,用数组book[i]记录从 0 到 i 的前缀和,再用数组mapp[i]记录前缀和为 i 时的位置,只有当book[j] == book[i] (j > i)时,子串中的 ‘0’ 和 ‘1’ 数量相等,此时更新 maxx=max(maxx,j-mapp[book[j]])。

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn=1e5+20;
    char s[maxn];
    int t,mapp[maxn*2],book[maxn*2],n,maxx;
    int main()
    {
        scanf("%d",&n);
        scanf("%s",s);
        book[0]=maxn;
        mapp[book[0]]=0;
        for(int i=0; i<n; i++)
        {
            if(s[i]=='0')
                book[i+1]=book[i]-1,t++;
            else
                book[i+1]=book[i]+1;
            if(mapp[book[i+1]]==0&&book[i+1]!=maxn)
                mapp[book[i+1]]=i+1;
            else
                maxx=max(maxx,i+1-mapp[book[i+1]]);
        }
        if(t>n-t)
            t=n-t;
        printf("%d %d
    ",maxx,t*2);
        return 0;
    }
  • 相关阅读:
    Java实现连接FTP服务并传递文件
    消息队列(MQ)入门-activemq,rocketmq代码级别
    js分页功能实现
    记录几个遇到的问题和解决方法
    oracle 日志归档设置
    打印系统时间
    linux 定时任务
    linux 安装jdk
    db2 命令
    二维码、条形码扫描——使用Google ZXing
  • 原文地址:https://www.cnblogs.com/Aamir-Dan/p/11264631.html
Copyright © 2011-2022 走看看