http://acm.hdu.edu.cn/showproblem.php?pid=1003
給你一串數列,讓你求出其中 一段連續的子數列 並且 該子數列所有數字之和最大,輸出該子數列的和、起點與終點序號。
具體細節不再贅述,看原題就好了。
說實話我覺得這個題有點難。。。想了好久,智商不夠。。。
但實際的代碼還算是相當簡單的,主要的邏輯就在中間那兩個 if 裡了,仔細看看就能理解了。
#include<stdio.h>
#include<string.h>
int main()
{
int lop, test_case, test_case_timer = 0;
int input_count, number[100000];
int max, first, last, temp, sum;
scanf("%d", &test_case);
while (test_case_timer < test_case)
{
memset(number, 0, sizeof(number));
first = 0;
last = 0;
temp = 0;
sum = 0;
max = -1001;
scanf("%d", &input_count);
for (lop = 0; lop < input_count; lop++)
{
scanf("%d", &number[lop]);
sum += number[lop];
if (sum > max)
{
max = sum;
first = temp;
last = lop;
}
if (sum < 0)
{
sum = 0;
temp = lop + 1;
}
}
printf("Case %d:\n", test_case_timer+1);
printf("%d %d %d\n", max, first + 1, last + 1);
if (++test_case_timer != test_case)
{
printf("\n");
}
}
return 0;
}