51Node 1065----最小正子段和

本文介绍了一种求解最小正子段和的算法实现,针对由N个整数构成的序列,寻找和大于0的子序列中和最小的一个。通过前缀和排序及两层遍历的方法找到符合条件的子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

51Node 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
输出最小正子段和。
Input示例
8
4
-1
5
-2
-1
2
6
-2
Output示例
1

代码如下:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
struct node
{
    LL m;
    int pos;
} A[50005];

bool cmp(const node x,const node y)
{
    return x.m<y.m;
}

int main()
{
    int N;
    while(scanf("%d",&N)!=EOF)
    {
        A[0].m=0;
        A[0].pos=0;
        for(int i=1; i<=N; i++)
        {
            LL x;
            scanf("%lld",&x);
            A[i].m=A[i-1].m+x;
            A[i].pos=i;
        }
        sort(A,A+N+1,cmp);
        LL t=999999999999;
        for(int i=1; i<=N; i++)
        {
            for(int j=i-1; j>=0; j--)
            {
                LL tmp=A[i].m-A[i-1].m;
                if(A[i].pos<A[i-1].pos)
                    tmp=0-tmp;
                if(tmp>0)
                {
                     t=min(t,tmp);
                     break;
                }
            }
        }
        cout<<t<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值