Maximum Subarray的題目,因為有 "If more than one segment is maximally nice, choose the one with the longest cycle ride (largest j-i). To break ties in longest maximal segments, choose the segment that begins with the earliest stop (lowest i)." 這個條件,所以必須開四個變數分別紀錄:
(1) Maximum Subarray的頭、尾
(2) 目前計算的Subarray的頭、尾
#include <stdio.h>
int main(void)
{
int i, n, m, t, , p, q, val, sum, max, stop, start;
scanf("%d", &n);
for (t = 1; t <= n; t++)
{
scanf("%d", &m);
max = sum = 0;
p = q = start = stop = 1;
for (i = 1; i < m; i++)
{
scanf("%d", &val);
sum += val;
if (sum >= 0)
{
q = i+1;
if ((sum > max) || (sum == max && q-p > stop-start))
{
max = sum;
start = p;
stop = q;
}
}
else
{
sum = 0;
p = q = i+1;
}
}
if (max)
printf("The nicest part of route %d is between stops %d and %d\n", t, start, stop);
else
printf("Route %d has no nice parts\n", t);
}
return 0;
}
沒有留言:
張貼留言