# Myers’diff

## 逆向算法

Myers'Diff之贪婪算反 是从(0,0)(N,M)进行移动的，它的反向工作是从(N,M)(0,0)

#### Middle Snake

for d = 0 to ( N + M + 1 ) / 2
{
for k = -d to d step 2
{
calculate the furthest reaching forward and reverse paths
if there is an overlap, we have a middle snake
}
}


#### Odd and Even Deltas

delta = N - M
for d = 0 to ( N + M + 1 ) / 2
{
for k = -d to d step 2
{
calculate the furthest reaching forward path on line k
if delta is odd and ( k >= delta - ( d - 1 ) and k <= delta + ( d - 1 ) )
if overlap with reverse[ d - 1 ] on line k
=> found middle snake and SES of length 2D - 1
}

for k = -d to d step 2
{
calculate the furthest reaching reverse path on line k
if delta is even and ( k >= -d - delta and k <= d - delta )
if overlap with forward[ d ] on line k
=> found middle snake and SES of length 2D
}
}

• (N+M+1) / 2 从两端同时出发，意味着外循环次数大于等于最长路径的二分之一；
• 如果delta 是偶数那么中间路径在向前的方向中出现；
• 如果delta 是偶数那么中间路径在向后的方向中出现；

### 递归解决

Compare( A, N, B, M )
{
if ( M == 0 && N > 0 ) add N deletions to SES
if ( N == 0 && M > 0 ) add M insertions to SES
if ( N == 0 || M == 0 ) return
calculate middle snake
suppose it is from ( x, y ) to ( u, v ) with total differences D
if ( D > 1 )
{
Compare( A[ 1 .. x ], x, B[ 1 .. y ], y ) // top left
Compare( A[ u + 1 .. N ], N - u, B[ v + 1 .. M ], M - v ) // bottom right
}
else if ( D == 1 ) // must be forward snake
{
Add d = 0 diagonal to results
}
else if ( D == 0 ) // must be reverse snake
{
}
}


02-13 517
05-26 1324
06-01 1075
05-26 912
02-14 276
04-03 1746
10-23