原题:
Given a sequence of K integers { N1, N2, ..., NK }. A continuous subsequence is defined 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.
Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence.
Input Specification:
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.
Output Specification:
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 and 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.
Sample Input:
10 -10 1 2 3 4 -5 -23 3 7 -21
结尾无空行
Sample Output:
10 1 4
结尾无空行
题目分析
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 and j (as shown by the sample case).
(意思是如果有多个子序列,那么输出i,j最小的,可以理解为做左到右最先找到的那个子序列)
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.
(如果给出的数字全为负数,可以理解为找的最大子序列为负数,所以我初始定义MaxSum=-1。此时,最后定义最大子序列为0,输出数组的第一个和最后一个数字)
答案(AC)
#include <stdio.h>
int main(){
int K;
int i,j;
int ThisSum=0;
int MaxSum=-1;
int head,tail,temp_head,flag=0,rflag=1;
scanf("%d",&K);
int subs[K];
for(i=0;i<K;i++){
scanf("%d",&subs[i]);
ThisSum+=subs[i];
if(!flag){
temp_head=subs[i];//record the temp head
flag=1;
}
if(ThisSum>MaxSum){
MaxSum=ThisSum;
tail=subs[i];//record the tail
head=temp_head;//record the head
rflag=0;
}
if(ThisSum<0){//update the ThisSum
ThisSum=0;
flag=0;
}
}
if(rflag){
head=subs[0];
tail=subs[K-1];
MaxSum=0;
}
printf("%d %d %d",MaxSum,head,tail);
return 0;
}
需要注意的是测试点5,一开始我把MaxSum初始定义为0,导致无法通过。这是因为当数组中有0的时候,头和尾的数字也会更新为0,而并非直接为第一个和最后一个数字。