• hdu 5783 Divide the Sequence 贪心


    Divide the Sequence

    题目连接:

    http://acm.hdu.edu.cn/showproblem.php?pid=5783

    Description

    Alice has a sequence A, She wants to split A into as much as possible continuous subsequences, satisfying that for each subsequence, every its prefix sum is not small than 0.

    Input

    The input consists of multiple test cases.
    Each test case begin with an integer n in a single line.
    The next line contains n integers A1,A2⋯An.
    1≤n≤1e6
    −10000≤A[i]≤10000
    You can assume that there is at least one solution.

    Output

    For each test case, output an integer indicates the maximum number of sequence division.

    Sample Input

    6
    1 2 3 4 5 6
    4
    1 2 -3 0
    5
    0 0 0 0 0

    Sample Output

    6
    2
    5

    Hint

    题意

    说的是,给你n个数,让你分成最多的块,使得每一块的任何前缀,都是大于0的。

    问你最多分成多少块

    题解:

    把长度为n的序列分成尽量多的连续段,使得每一段的每个前缀和都不小于0。保证有解。 从后往前贪心分段即可。

    代码

    #include<bits/stdc++.h>
    using namespace std;
    const int maxn = 1e6+7;
    int n;
    long long a[maxn];
    int main(){
        while(scanf("%d",&n)!=EOF){
            for(int i=1;i<=n;i++){
                scanf("%I64d",&a[i]);
            }
            long long flag = 0;
            long long ans = 0;
            long long now = 0;
            for(int i=n;i>=1;i--){
                if(flag==0&&a[i]>=0){
                    ans++;
                    flag = 0;
                }
                else if(flag==0&&a[i]<0){
                    flag=1;
                    now+=a[i];
                    ans++;
                }else if(flag==1){
                    now+=a[i];
                    if(now>=0){
                        now=0,flag=0;
                    }
                }
            }
            cout<<ans<<endl;
        }
    }
  • 相关阅读:
    OpenSSL证书生成
    支付宝支付流程
    前端获取用户位置信息
    微信公众号开发(三)
    微信公众号开发(二)
    微信公众号开发(一)
    前端优化
    页面自适应
    CSS样式(二)
    CSS样式(一)
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5730380.html
Copyright © 2020-2023  润新知