标签:
Description
Input
Output
Sample Input
Sample Output
这是一道求最大子序列和的题。
思路就是考虑到对于S(i...k) + S(k+1...j) = S(i...j),如果S(i...k)小于0,自然考虑S(k+1...j)这段和;反之,考虑S(i...j)。
于是从1到n,判断当前的S(i...k)是否小于0,大于0则保留,否则舍去。
考虑到可能整个过程可能S(i...k)一直小于0,所以即使小于0,也要保留当前值now,将其与ans比较。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <map>
#include <vector>
using namespace std;
int n;
int ans, from, to;
void Work()
{
from = -1;
to = -1;
int k, now, u = -1, v = -1;
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
{
scanf("%d", &k);
if (u == -1 || now < 0 || now+k < 0)
{
u = v = i;
now = k;
}
else
{
v = i;
now = now+k;
}
if (from == -1 || now > ans)
{
ans = now;
from = u;
to = v;
}
}
}
int main()
{
//freopen("test.in", "r", stdin);
int T;
scanf("%d", &T);
for (int times = 1; times <= T; ++times)
{
Work();
if (times != 1)
printf("\n");
printf("Case %d:\n", times);
printf("%d %d %d\n", ans, from, to);
}
return 0;
}
ACM学习历程—HDU1003 Max Sum(dp && 最大子序列和)
标签:
原文地址:http://www.cnblogs.com/andyqsmart/p/4498127.html