I've confused with the code that is written in the TEXT Dynamic Programming section of USACO Training about a classical problem (Finding Maximum Decreasing Subsequence). This is Article Link. Please help me to get it!
Here's the code:
1 #include <stdio.h>
2 #define MAXN 200000
3 main () {
4 FILE *in, *out;
5 long num[MAXN], bestrun[MAXN];
6 long n, i, j, highestrun = 0;
7 in = fopen ("input.txt", "r");
8 out = fopen ("output.txt", "w");
9 fscanf(in, "%ld", &n);
10 for (i = 0; i < n; i++) fscanf(in, "%ld", &num[i]);
11 bestrun[0] = num[n-1];
12 highestrun = 1;
13 for (i = n-1-1; i >= 0; i--) {
14 if (num[i] < bestrun[0]) {
15 bestrun[0] = num[i];
16 continue;
17 }
18 for (j = highestrun - 1; j >= 0; j--) {
19 if (num[i] > bestrun[j]) {
20 if (j == highestrun - 1 || num[i] < bestrun[j+1]){
21 bestrun[++j] = num[i];
22 if (j == highestrun) highestrun++;
23 break;
24 }
25 }
26 }
27 }
28 printf("best is %d\n", highestrun);
29 exit(0);
30 }
I have 3 problems with it:
1) What exactly lines 14-17 do? For example for the sequence 10, 2, 8, 9, 4, 6, 3 , the result of the that code is 4 but it's subsequence is 10, 8, 4, 2 that it's wrong, because the element 2 in original sequence is before 8 and 4 but in the resulting subsequence is after 8 and 4!
2) Consider the sequence 5, 10, 8, 9, 4, 6, 3. According to above code, the length of the maximum decreasing subsequence is 4 and this subsequence is 10, 5, 4, 3. But in this subsequence opposite of the original sequence 5 is after 10.
3) Is it necessary to check num[i] < bestrun[j+1]
condition in inner loop? I think it's satisfied before by num[i] > bestrun[j]
condition.
I'm waiting for you helpful answers.
Thanks for your help!
1) bestrun[i]
keeps track of the smallest integer that is the start of a longest decreasing subsequence of length i + 1. Therefore, if you encounter a value that is smaller than your current bestrun[0]
, you want to change bestrun[0]
to that value, as that would be the the smallest decreasing subsequence of length 1.
2) I'm not particularly sure what you're asking. If you're wondering about what happens when you flip the sequence around, then you could run the longest increasing subsequence algorithm instead to get the same result.
3) Yes, that seems to be redundant, as bestrun
should be nonincreasing. In fact, some implementations of longest increasing/decreasing subsequence exploit this fact to improve runtime to O(n log n) by doing a binary search to find the highest j
such that num[i]
is bigger than bestrun[j]
.