Today, when looking at the code source file to find the principle of diff, I saw the LCS algorithm. This algorithm should be no stranger to the classic algorithm of motion rules. Specific algorithm do what I will not say, do not know can directly see the "Introduction to the algorithm" dynamic planning that chapter. Now that I have seen it, I want to recall that when we think of the correctness of the algorithm, we find that the correctness of this algorithm proves to be not good. So thought for a period of time, inside there are a few details very trick, easy to sink in. Think of a few rounds, now put the proof posted, there are objections can be exchanged messages together.
First, some symbols and conventions are described below:
Suppose there are two arrays, A and B. A[i] is the first element of a, a (i) is a prefix consisting of the first element of a to the I element. M (i, J) is the longest common sub-sequence length of a (i) and B (j).
Because the recursive nature of the algorithm itself, in fact, as long as the proof, for some I and J:
M (i, j) = m (i-1, j-1) + 1 (when a[i] = B[j])
M (i, j) = Max (M (I-1, J), M (I, j-1)) (when a[i]! = B[j])
The first is a good proof, that is, when a[i] = B[j]. Can be disproved, assuming M (i, J) > m (i-1, j-1) + 1 (M (i, J) cannot be less than M (i-1, j-1) + 1, the reason is obvious), then can be introduced m (I-1, j-1) is not the longest of this contradictory result.
The second one has some trick. When a[i]! = B[j], it is still a rebuttal, assuming M (i, J) > Max (M (I-1, J), M (I, j-1)).
From the counter-disprove hypothesis, M (i, J) > m (i-1, J) are available. This can be rolled out a[i] must be in M (i, J) corresponding to the LCS sequence (to be disproved). And because a[i]! = B[j], so b[j] must not be in M (i, J) corresponding to the LCS sequence. So I can eject M (i, j) = m (i, j-1). This introduces the result of contradictory assumptions.
Evidence.
Validity proof of LCS (longest common subsequence) dynamic regulation algorithm