标签:ref with one pos bre max sum -o second 条件
目录
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.
给出一个序列a[1],a[2],a[3]......a[n],你的任务是计算子序列的最大和,例如,对于(6,-1,5,4,-7),最大和是这个子序列6 + (-1) + 5 + 4 = 14
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).
第一行包括一个整数T(1<=T<=20),代表测试用例的数量。接下来的T行,每行开始于一个数N(1<=N<=100000),然后跟着N个数,所有的整数都在 -1000 and 1000
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.
对于每个测试用例,你应该输出两行。第一行是Case #:,#代表测试用例的序号。第二行包括三个数,序列最大和,还有这个子序列的开始和结束坐标。如果有超过一个以上的结果,输出第一个即可。在两个用例之间输出一个空行。
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Case 1:
14 1 4
Case 2:
7 1 6
典型的动态规划问题,可参见【最长子序列和】。
本题要求输出满足条件的子序列区间,一个for循环就可以搞定
//HDU 1003 VELSCODE VER1.0
#include <iostream>
using namespace std;
int T,N,max1[20],L[20],R[20];
int A[100000],DP[100000];
int main()
{
//input
scanf("%d",&T);
for( int t=0;t<T;t++ )
{
scanf("%d",&N);
for( int i = 0; i < N; i++ )
{
scanf("%d",&A[i]);
}
//dp
DP[0] = A[0];
for(int i=1;i<N;i++)
{
if( A[i] > DP[i-1]+A[i] )
{
DP[i] = A[i];
}
else //A[i] < DP[i-1]+A[i]
{
DP[i] = DP[i-1]+A[i];
}
}
//寻找最大值
int pos = 0;
max1[t] = DP[0];
for(int i=0;i<N;i++ )
{
if( max1[t] < DP[i] )
{
max1[t] = DP[i];
pos = i;
}
}
//寻找子序列左右坐标
R[t] = pos;
L[t] = pos;
for( int i = pos - 1 ; i >= 0 ;i-- )
{
if( DP[i] >= 0 )
{
L[t] = i;
}
else
break;
}
}
//output
for( int i = 0; i < T; i++ )
{
printf("Case %d:\n",i+1);
printf("%d %d %d\n",max1[i],L[i]+1,R[i]+1);
if( i != T-1 )
printf("\n");
}
}
标签:ref with one pos bre max sum -o second 条件
原文地址:https://www.cnblogs.com/velscode/p/10072309.html