zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    Asp.Net Core 2.0 之旅---在Ubuntu上部署WEB应用程序
    xml对象序列化
    txt文本文件记录日志
    HttpGet HttpPost
    c# MD5
    10位时间戳转为C#格式时间
    树莓派上运行.net core 2.0程序
    c# 解析json
    小程序与后台数据交互时出现乱码时
    小程序template怎样渲染页面的
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5730380.html
Copyright © 2011-2022 走看看