学习动态规划,就选了一些动态规划的ACM题目练练,这是一道比较简单的题目
我是通过在输入元素的时候就开始计算比较,结构体记录最大子段和的首尾位置
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.
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).
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.
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
#include<stdio.h>
struct location {
int first;
int end;
};
int main(void) {
int MaxSum , sum;
int casenum , n;
int a[100005] , i , j;
location maxloc , nowloc;
scanf("%d" , &casenum);
for(i=1 ; i<=casenum ; i++) {
scanf("%d" , &n);
MaxSum = -10001;
sum = -10001;
nowloc.first = 1;
nowloc.end = 1;
for(j=1;j<=n;j++) {
scanf("%d" , &a[j]);
if(sum < 0) {
sum = a[j];
nowloc.first = j;
nowloc.end = j;
if(sum > MaxSum) {
MaxSum = sum;
maxloc.first = nowloc.first;
maxloc.end = nowloc.end;
}
} else {
sum += a[j];
nowloc.end = j;
if(sum > MaxSum) {
MaxSum = sum;
maxloc.first = nowloc.first;
maxloc.end = nowloc.end;
}
}
}
printf("Case %d:\n" , i);
printf("%d %d %d\n" , MaxSum , maxloc.first , maxloc.end);
if(i != casenum) {
printf("\n");
}
}
return 0;
}