SDAU dp专题 1001

来源:互联网 发布:eviews时间序列数据 编辑:程序博客网 时间:2024/05/27 19:27

1:问题描述
Problem Description
Given a sequence a[1],a[2],a[3]……a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).

Output
For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.

Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5

Sample Output
Case 1:
14 1 4

Case 2:
7 1 6

2:大致题意

给出一个序列,求出子序列和的最大值~

3:思路

从头开始加,每次求和都判断是不是小于0,如果小于0,就舍去前面所有的,因为小于0的数,加上后面的肯定会使后面的数变小。
还要记录下来最大值,如果加上后面的数,没有最大值 大,就没必要改变起始位置。
注意要改变起点和终点。

4:感想

现在想起来挺简单的,当时做的时候想了很长时间~

5:ac代码

#include<iostream>#include<string.h>#include<set>#include<stdio.h>#include<vector>#include<algorithm>#include<numeric>#include<math.h>#include<string.h>#include<sstream>#include<stdio.h>#include<string>#include<cstdlib>#include<algorithm>#include<iostream>#include<map>#include<queue>#include<iomanip>#include<cstdio>using namespace std;int main(){    //freopen("r.txt","r",stdin);    int n,m,sum,maxx,j,k;    int a[100005];    cin>>n;    int ans=1,step;    while(n--)    {        cin>>m;        for(int i=0;i<m;i++)        {            scanf("%d",&a[i]);        }        sum=0;        maxx=-1001;        step=1;        for(int i=0;i<m;i++)        {            sum+=a[i];                if(sum>maxx)                    {                        j=step;                        k=i+1;                        maxx=sum;                    }            if(sum<0)            {                sum=0;                step=i+2;            }        }        cout<<"Case "<<ans++<<":"<<endl;        cout<<maxx<<" "<<j<<" "<<k<<endl;        if(n>0) cout<<endl;    }    return 0;}
0 0
原创粉丝点击