1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| #include <stdio.h>
int MinSubsequence(int *arr, int head, int tail) { if (head == tail) { return arr[head]; } int mid = (head + tail) / 2; int leftMin = MinSubsequence(arr, head, mid); int rightMin = MinSubsequence(arr, mid + 1, tail); int cLmin = 1000000; int cRmin = 1000000; int tempSum = 0; for (int p = mid; p >= head; p--) { tempSum += arr[p]; if (tempSum < cLmin) { cLmin = tempSum; } } tempSum = 0; for (int p = mid + 1; p <= tail; p++) { tempSum += arr[p]; if (tempSum < cRmin) { cRmin = tempSum; } } if (leftMin <= rightMin && leftMin <= cLmin + cRmin) { return leftMin; } else if (rightMin <= leftMin && rightMin <= cLmin + cRmin) { return rightMin; } else { return cLmin + cRmin; }
}
int main() { int A[] = {-43, 45, 5, -46, 20, 4, 43, -16, 41, 31, -28, -38, 4, 14, -49}; int B[] = {16, -33, 40, -17, 40, 36, 40, 9, -14, 23, -40, 11, -10, -25, -28}; int C[] = {46, -39, -14, 12, 8, -7, 25, -47, 36, 26, 28, 17, -41, 14, 47}; int D[] = {-3, 35, 6, 47, 7, -45, -34, -37, -26, -25, -4, -23, 38, -20, 24}; int E[] = {-48, -40, -4, -4, -42, -35, -8, 39, -36, -39, -43, 42, 23, 37, -4};
printf("A: %d\n", MinSubsequence(A, 0, 14)); printf("B: %d\n", MinSubsequence(B, 0, 14)); printf("C: %d\n", MinSubsequence(C, 0, 14)); printf("D: %d\n", MinSubsequence(D, 0, 14)); printf("E: %d\n", MinSubsequence(E, 0, 14));
return 0; }
|