题解:这道题目是关于dp和背包的一个题目,要求的是最长公共子序列(简称LCS),设置一个标记数组b一个存储二维数组c,分为三种情况当b[i]==b[j]时c[i][j]+=1 如果讲b[i][j]变为0,当前一个比后面的长的时候即c[i-1][j-1]<=c[i][j]时候max(c[i][j],c[i-1][j-1]) 其他情况保持不变c[i][j]=c[i][j-1]
相当于找到对角的最长的序列
废话不多说,贴代码
#include <stdio.h>
#include <string.h>
#include<bits/stdc++.h>
#define MAXLEN 1010
using namespace std;
void LCSLength(char *x, char *y, int m, int n, int c[][MAXLEN], int b[][MAXLEN])
{
int i, j;
for(i = 0; i <= m; i++)
c[i][0] = 0;
for(j = 1; j <= n; j++)
c[0][j] = 0;
for(i = 1; i<= m; i++)
{
for(j = 1; j <= n; j++)
{
if(x[i-1] == y[j-1])
{
c[i][j] = c[i-1][j-1] + 1;
b[i][j] = 0;
}
else if(c[i-1][j] >= c[i][j-1])
{
c[i][j] = c[i-1][j];
b[i][j] = 1;
}
else
{
c[i][j] = c[i][j-1];
b[i][j] = -1;
}
}
}
}
void PrintLCS(int b[][MAXLEN], char *x, int i, int j)
{
if(i == 0 || j == 0)
return;
if(b[i][j] == 0)
{
PrintLCS(b, x, i-1, j-1);
printf("%c", x[i-1]);
}
else if(b[i][j] == 1)
PrintLCS(b, x, i-1, j);
else
PrintLCS(b, x, i, j-1);
}
int main(int argc, char **argv)
{
char x[MAXLEN] ;
char y[MAXLEN] ;
int b[MAXLEN][MAXLEN];
int c[MAXLEN][MAXLEN];
cin>>x>>y;
int m, n;
m = strlen(x);
n = strlen(y);
LCSLength(x, y, m, n, c, b);
PrintLCS(b, x, m, n);
return 0;
}