题目描述:
Given a sequence of K integers {N1,N2,……,Nk}. A continuous subsequence is definded to be{Ni,Ni+1,……Nj} where 1<=i<=j<=k. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence{-2,11,-4,13,-5,-2}, its maximum subsequence is {11,-4,13} with the largest sum being 20.
输入格式:
Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K(<=10000). The second line contains K numbers, separated by a space.
输出格式:
For each test case, output in one line the largest sum,together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i an j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.
样例输入:
10
-10 1 2 3 4 -5 -23 3 7 -21
样例输出:
10 1 4
实现代码:
#include<stdio.h>
#include<iostream>
using namespace std;
const int maxn = 10010;
int a[maxn];//用来存放序列
int dp[maxn];//用来存放以a[i]结尾的连续序列的最大和
int s[maxn];//连续序列从a的哪一个元素开始
int main(){
//开始的输入
int n;
scanf("%d",&n);
bool flag = true;//flag表示数组a中是否全小于0
for(int i = 0; i < n; ++i){//读入序列
scanf("%d",&a[i]);
if(a[i] >= 0) flag = false;
}
//ȫΪ¸ºÊýµÄÊä³öÇé¿ö
if(flag == true){
printf("0 %d %d", a[0], a[n-1]);
return 0;//现在感觉return 0就是程序结束的标志了
}
//边界条件
dp[0] = a[0];
for(int i = 1; i <= n; ++i){
//状态转移方程
if(a[i] < dp[i-1] + a[i]){//*****五星好评,a[i]也是一个子串
dp[i] = dp[i-1] + a[i];
s[i] = s[i-1];
}
else{
dp[i] = a[i];
s[i] = i;
}
}
//找出最后的值
int max = 0;
for(int i = 0; i < n; ++i){
if(dp[i] > dp[max]) max = i;//找出最大值
}
printf("%d %d %d",dp[max],a[s[max]],a[max]);//a[s[max]]这种形式目前还是挺少见的
return 0;
}
总结:挺难的,模板是需要背的