您的位置:首页 > 其它

max sum(动态规划求最大连续子序列)

2016-08-13 15:11 337 查看
题意:给出一个序列,求这个序列的最大连续子序列。

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1003

思路:从输入开始,四个变量:
ma:记录每次的最大值。
st:序列开始,当res小于0时,从下一个开始。
en:序列尾,每当当前值大于原先的ma时,en就等于当前,不能直接令en加1。
res : 记录每次加上输入的值后的总值,以res判定是否大于原先的最大值,如果是的话,将该点加入,判定res是否小于0,如果是的话则将res至0,并重新从下一点开始。(一开始想如果全部是负数该怎么办,但全部是负数的话,就找最大的那个负数就好了)


代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int INF = -1e4;
const int maxn = 1e5+10;
int main()
{
int t,c=0;
cin >> t;
while(t--)
{
int n,res = 0,ma = INF;
cin >> n;
int st = 0, en = 0;
for(int i=0; i<n; i++)
{
int a;
scanf("%d",&a);
res += a;
if(res > ma)
{
ma = res; en = i;
}
if(res < 0)
{
res = 0; st = i+1;
}
}
printf("Case %d:\n",++c);
printf("%d %d %d\n",ma,st+1,en+1);
if(t != 0)
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: