HDU-1231-最大连续子序列【dp】

来源:互联网 发布:质数优化算法 编辑:程序博客网 时间:2024/04/29 07:39

HDU-1231-最大连续子序列


            Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Problem Description
给定K个整数的序列{ N1, N2, …, NK },其任意连续子序列可表示为{ Ni, Ni+1, …,
Nj },其中 1 <= i <= j <= K。最大连续子序列是所有连续子序列中元素和最大的一个,
例如给定序列{ -2, 11, -4, 13, -5, -2 },其最大连续子序列为{ 11, -4, 13 },最大和
为20。
在今年的数据结构考卷中,要求编写程序得到最大和,现在增加一个要求,即还需要输出该
子序列的第一个和最后一个元素。

Input
测试输入包含若干测试用例,每个测试用例占2行,第1行给出正整数K( < 10000 ),第2行给出K个整数,中间用空格分隔。当K为0时,输入结束,该用例不被处理。

Output
对每个测试用例,在1行里输出最大和、最大连续子序列的第一个和最后一个元
素,中间用空格分隔。如果最大连续子序列不唯一,则输出序号i和j最小的那个(如输入样例的第2、3组)。若所有K个元素都是负数,则定义其最大和为0,输出整个序列的首尾元素。

Sample Input
6
-2 11 -4 13 -5 -2
10
-10 1 2 3 4 -5 -23 3 7 -21
6
5 -8 3 2 5 0
1
10
3
-1 -5 -2
3
-1 0 -2
0

Sample Output
20 11 13
10 1 4
10 3 5
10 10 10
0 -1 -2
0 0 0

题目链接:HDU-1231

题目思路:

    状态转移方程:dp[i] = max(dp[i - 1] + num[i],num[i]) //取第i个位置的最大连续子序列的和

两种情况:
1.把第i个位置的数加入前面的序列中
2.以第i个位置为起点
另外,需要记录每个子序列的起始点,

注意当数字全部为附属的时候最大和为0,并输出该序列第一个位置和最后一个位置

以下是代码:

#include <vector>#include <map>#include <set>#include <algorithm>#include <iostream>#include <cstdio>#include <cmath>#include <cstdlib>#include <string>#include <cstring>using namespace std;int num[10010];int dp[10010];int pos[10010]; //记录起始点 int main(){    int n;    while(cin >> n && n)    {        memset(num,0,sizeof(num));        memset(dp,0,sizeof(dp));        memset(pos,0,sizeof(pos));        for (int i = 0; i < n; i++)        {            cin >> num[i];        }        pos[0] = num[0];        int ans = -100;        for (int i = 0; i < n; i++)        {            if (dp[i - 1] + num[i] > num[i])            {                pos[i] = pos[i - 1];            }            else            {                pos[i] = num[i];            }            dp[i] = max(dp[i - 1] + num[i],num[i]);            ans = max(ans,dp[i]);        }        if (ans < 0)        {            cout << 0 << " " << num[0] << " " << num[n - 1] << endl;             continue;        }        for (int i = 0; i < n; i++)        {            if (dp[i] == ans)            {                cout << dp[i] << " " << pos[i] << " " << num[i] << endl;                break;            }        }    }    return 0;}
0 0
原创粉丝点击