zoukankan      html  css  js  c++  java
  • 1065 最小正子段和

    N个整数组成的序列a[1],a[2],a[3],…,a[n],从中选出一个子序列(a[i],a[i+1],…a[j]),使这个子序列的和>0,并且这个和是所有和>0的子序列中最小的。
    例如:4,-1,5,-2,-1,2,6,-2。-1,5,-2,-1,序列和为1,是最小的。
    Input
    第1行:整数序列的长度N(2 <= N <= 50000)
    第2 - N+1行:N个整数
    Output
    输出最小正子段和。
    这题求最小的子序列。。我们先把每个区间的sum先求出来,然后把每个sum和对应的id按照sum的大小排个序。然后当sum[i].id<sum[i+1].id说明可以形成子序列。然后更新最小整子段和便可
    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    #include<iostream>
    using namespace std;
    const int N=55000;
    #define inf 0x3f3f3f3f3f3f
    int a[N];
    struct node
    {
         long long x;
         int id;
    };
    bool cmp(node a,node b)
    {
        return a.x<b.x;
    }
    node sum[N];
    int main()
    {
        int n;
        while(scanf("%d",&n)!=EOF)
        {
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);
            sum[0].x=a[0];
            sum[0].id=0;
            for(int i=1;i<n;i++)
            {
                sum[i].x=sum[i-1].x+a[i];
                sum[i].id=i;
            }
            sort(sum,sum+n,cmp);
            long long ans=inf;
            for(int i=0;i<n-1;i++)
            {
                if(sum[i].x>0)
                    ans=min(sum[i].x,ans);
                if(sum[i+1].x>0)
                    ans=min(ans,sum[i+1].x);
                if(sum[i].id<sum[i+1].id)
                {
                    long long tmp=sum[i+1].x-sum[i].x;
                    if(tmp>0)
                    {
                        if(tmp<ans)
                            ans=tmp;
                    }
                }
            }
            cout<<ans<<endl;
        }
        return 0;
    }
    


  • 相关阅读:
    jsp Ajax请求(返回xml数据类型)
    springboot整合mybatis
    springboot使用jdbcTemplate案例
    springboot使用jpa案例
    使用SpringBoot访问jsp页面
    SpringBoot使用thymeleaf案例
    SpringBoot
    Dobbox
    Spring Jpa
    SSM整合Dubbo登陆案例
  • 原文地址:https://www.cnblogs.com/NaCl/p/9580134.html
Copyright © 2011-2022 走看看