HDU 1159 Common Subsequence(LCS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35691619/article/details/78876699

当s1[s]=s2[t]时,在公共子串末尾加上s1[s]

当s1[s]!=s2[t]时,s1当前长度减1与s2比;s2当前长度减1与s1比

if (s1[s] == s2[t]) {
                dp[s+1][t+1] = dp[s][t] + 1;
            } else {
                dp[s+1][t+1] = max(dp[s][t+1], dp[s+1][t]);
            }



具体如下

#include<stdio.h>
#include<string.h>


char s1[1005], s2[1005];
int dp[1005][1005];
int max(int a, int b) {
    return a>b?a:b;
}

void solve() {
    for (int s = 0; s < strlen(s1); s++) {
        for (int t = 0; t < strlen(s2); t++) {
            if (s1[s] == s2[t]) {
                dp[s+1][t+1] = dp[s][t] + 1;
            } else {
                dp[s+1][t+1] = max(dp[s][t+1], dp[s+1][t]);
            }
        }
    }

    printf("%d\n", dp[strlen(s1)][strlen(s2)]);
}



int main(void)
{
    while (scanf("%s %s", s1, s2) != EOF) {
            memset(dp, 0, sizeof(dp));
            solve();
    }

    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_35691619/article/details/78876699