debug d死人系列
LCS具体详解请看算法导论!!!
就是LCS的查找和输出
照着伪代码一模一样先打上去的
稍微不一样的是也要输出不是公共的字符串
然后就被坑在这里了(哭唧唧)
开始没法输出前面的几个字符
以为把递归终止的界限放宽:if ( i < 0 && j < 0 )就能行了
但有时候会造成segmentation fault
gdb之后才发现是i会持续-1一直到无穷的负数,但j一直>0
改来改去最后实在不行
才有了现在看到的判断方式
成功……..
#include <cstdio>
#include <cstring>
#include <iostream>
#define N 105
using namespace std;
int len1, len2;
char s1[ N ], s2[ N ];
int DP[ N ][ N ];
inline int max ( int a, int b ) { return a > b ? a : b; }
void LCS () {
for ( int i = 1; i <= len1; i++ ) {
for ( int j = 1; j <= len2; j++ ) {
if ( s1[ i ] == s2[ j ] )
DP[ i ][ j ] = DP[ i - 1 ][ j - 1 ] + 1;
else
DP[ i ][ j ] = max ( DP[ i - 1 ][ j ], DP[ i ][ j - 1 ] );
}
}
}
void Print ( int i, int j ) {
//当最长的子序列搜索完,但其中一串仍有剩余时,输出
if ( i == 0 || j == 0 ) {
if ( i == 0 )
for ( int k = 1; k <= j; k++ )
printf ( "%c", s2[ k ] );
if ( j == 0 )
for ( int k = 1; k <= i; k++ )
printf ( "%c", s1[ k ] );
return;
}
//找到公共字符
if ( s1[ i ] == s2[ j ] ) {
Print ( i - 1, j - 1 );
printf ( "%c", s1[ i ] );
} else if ( DP[ i - 1 ][ j ] > DP[ i ][ j - 1 ] ) {
Print ( i - 1, j );
printf ( "%c", s1[ i ] );
} else {
Print ( i, j - 1 );
printf ( "%c", s2[ j ] );
}
}
int main () {
while ( ~scanf ( "%s%s", s1 + 1, s2 + 1 ) ) {
len1 = strlen ( s1 + 1 );
len2 = strlen ( s2 + 1 );
memset ( DP, 0, sizeof ( DP ) );
LCS ();
Print ( len1, len2 );
printf ( "\n" );
}
return 0;
}