题目链接:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1006
给出两个字符串A B,求A与B的最长公共子序列(子序列不要求是连续的)。
比如两个串为:
abcicba
abdkscab
ab是两个串的子序列,abc也是,abca也是,其中abca是这两个字符串最长的子序列。
Input
第1行:字符串A 第2行:字符串B (A,B的长度 <= 1000)Output
输出最长的子序列,如果有多个,随意输出1个。Input示例
abcicba abdkscabOutput示例
abca#include <stdio.h> #define MAXN 1002 char A[MAXN] = { 0 }; char B[MAXN] = { 0 }; char R[MAXN] = { 0 }; short mat[MAXN][MAXN] = { 0 }; //a串的前i个字母,b串的前j个字母相同的个数 //返回三个数的最大值 short max(short a, short b, short c) { if (a > b) { b = a; } return b > c ? b : c; } int main() { //freopen("C://input.txt", "r", stdin); int i, j = 0, k; scanf("%s %s", A + 1, B + 1); for (i = 1; A[i]; i++) { for (j = 1; B[j]; j++) { mat[i][j] = max(mat[i - 1][j], mat[i][j - 1], mat[i - 1][j - 1] + (A[i] == B[j])); } } i--; j--; k = 1; while (i > 0 && j > 0) { if (A[i] == B[j]) { R[k++] = A[i]; i--; j--; } else if (mat[i - 1][j] > mat[i][j - 1]) { i--; } else { j--; } } k--; for (int i = k; i > 0; i--) { printf("%c", R[i]); } printf("\n"); return 0; }
51nod 1006 最长公共子序列Lcs (dp)
猜你喜欢
转载自blog.csdn.net/Evildoer_llc/article/details/82976354
今日推荐
周排行