最大字段和&洛谷11月月赛DIV2 T1

蒟蒻只能打一打DIV2的基础题

太卑微了

这道题的本质其实是再建一个数组,如果s串i位置是0那么就给a[i]赋值为1,表示要累加个数,如果是1那么就把a[i]赋值为-1,表示个数减一,最后求最大子段和,那么就可以O(n)实现了。

附上最大子段和blog链接https://blog.csdn.net/weixin_40170902/article/details/80585218

#include<bits/stdc++.h>
#define R register int
using namespace std;
const int N=1e5+5;
inline int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9') {if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
    return x*f;
}
char s[N];
int a[N],n;
inline int DP()
{
    int temp=0,ans=-1;
    for(R i=1;i<=n;i++)
    {
        temp=(temp+a[i]>a[i])?(temp+a[i]):a[i];
        ans=max(temp,ans);
    }
    return ans;
}
int main()
{
    scanf("%s",s+1);
     n=strlen(s+1);
    for(R i=1;i<=n;i++)
    {
        if(s[i]=='0') a[i]=1;
        else a[i]=-1;
    }
    cout<<DP();
    return 0;
}

学会转化问题真的很重要啊

posted @ 2019-11-13 15:18  Gold_stein  阅读(143)  评论(0编辑  收藏  举报