1177: LFX学橙啦!题解

问题如下:先给你一个含有N个整数的数组数组中的每一个元素只为1或者0而N的大小为1~100你可以删除一些元素(也可以选择不删除),使剩下的数组中,没有一个元素0在1后面出现。并且要使剩下的元素的数量最多,请输出剩下元素的数量。

 

思路:

没有一个元素0在1后面出现,。

那么操作后的数组只可能是这个样子的:

0 0 0 0 1 1 1 1

或者 0 0 0 0 0  或者 1 1 1 1 1

那么我们只需要处理下这个数组的第i个位置的时候,1~i有多个0,显然用前缀和来维护。

再处理下这个数组的第i个位置的时候,i~n有多个1,显然用后缀和来维护。

那么我们扫一遍数组,在每一个位置i时,如果这个i为分界线,让0~i 只有0,i~n只有1.

那么第i个位置的时候答案就是presum[i]+dum[i].// 分别代表前缀和/后缀和数组

那么我们对1~n的每一个位置的答案取max,最大的就是题目的最优解,即答案。

细节见code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define ALL(x) (x).begin(), (x).end()
#define dll(x) scanf("%I64d",&x)
#define xll(x) printf("%I64d
",x)
#define sz(a) int(a.size())
#define all(a) a.begin(), a.end()
#define rep(i,x,n) for(int i=x;i<n;i++)
#define repd(i,x,n) for(int i=x;i<=n;i++)
#define pii pair<int,int>
#define pll pair<long long ,long long>
#define gbtb ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define MS0(X) memset((X), 0, sizeof((X)))
#define MSC0(X) memset((X), '', sizeof((X)))
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define eps 1e-6
#define gg(x) getInt(&x)
#define db(x) cout<<"== [ "<<x<<" ] =="<<endl;
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
ll powmod(ll a,ll b,ll MOD){ll ans=1ll;while(b){if(b&1)ans=ans*a%MOD;a=a*a%MOD;b>>=1;}return ans;}
inline void getInt(int* p);
const int maxn=1000010;
const int inf=0x3f3f3f3f;
/*** TEMPLATE CODE * * STARTS HERE ***/
int a[maxn];
int presum[maxn];// 0的数量的前缀和
int dum[maxn];// 1的数量的后缀和
int n;
int main()
{
    gbtb;
    cin>>n;
    repd(i,1,n)
    {
        cin>>a[i];
    }
    for(int i=n;i>=1;i--)
    {
        dum[i]=dum[i+1];
        if(a[i])
            dum[i]++;
    }
    repd(i,1,n)
    {
        presum[i]=presum[i-1];
        if(!a[i])
        {
            presum[i]++;
        }
    }
    int ans=0;
    repd(i,1,n)
    {
        ans=max(ans,presum[i]+dum[i]);
    }
    cout<<ans<<endl;
    return 0;
}

inline void getInt(int* p) {char ch;do {ch = getchar();}
while (ch == ' ' || ch == '
');if (ch == '-') {*p = -(getchar() - '0');
while ((ch = getchar()) >= '0' && ch <= '9') {*p = *p * 10 - ch + '0';}}
else {*p = ch - '0';while ((ch = getchar()) >= '0' && ch <= '9')
{*p = *p * 10 + ch - '0';}}}
本博客为本人原创,如需转载,请必须声明博客的源地址。 本人博客地址为:www.cnblogs.com/qieqiemin/ 希望所写的文章对您有帮助。
原文地址:https://www.cnblogs.com/qieqiemin/p/10513085.html