您的位置:首页 > 其它

51nod 1065 最小正子段和

2016-03-31 16:42 405 查看
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


思路:先计算出每位的前缀和, 然后再从小到大排序,然后遍历一遍, 如果该位的id 比前一位的id小, 那么前一位的肯定用不到, 那么只要判断该位的id大于前一位的,并且

和大于前一位的,(因为要求正的最xiao)。

注意:当遇到求连续序列的题目时, 应该第一时间考虑到前缀和, 太有用了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<stack>
#include <queue>
#include <set>
using namespace std;
const int inf = 2147483647;
const double PI = acos(-1.0);
const int mod = 1000000007;
struct node
{
long long v;
int id;
}a[50005];
bool cmp(node a, node b)
{
return a.v < b.v;
}
int main()
{
int n, i, j;
while (~scanf("%d", &n))
{
a[0].v = 0;
a[0].id = 0;
for (i = 1; i <= n; ++i)
{
scanf("%lld", &a[i].v);
a[i].v += a[i - 1].v;
a[i].id = i;
}
sort(a, a + 1 + n, cmp);
long long res = 99999999999999;
for (i = 1; i <= n; ++i)
{
if (a[i].v > a[i - 1].v && a[i].id > a[i - 1].id)
{
res = min(res, a[i].v - a[i - 1].v);
}
}
printf("%lld\n", res);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: