您的位置:首页 > Web前端 > Node.js

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

2016-07-02 18:35 369 查看
51Node 1065----最小正子段和
N个整数组成的序列a[1],a[2],a[3],…,a
,从中选出一个子序列(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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: