[DP-LCS] HDU1503

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值