caioj 1072 动态规划入门(二维一边推5:最长公共子序列 LCSS加强版)

在51nod刷到过同样的题,直接秒杀

https://blog.csdn.net/qq_34416123/article/details/81697683

#include<cstdio>
#include<cstring>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 1123;
char a[MAXN], b[MAXN];
int f[MAXN][MAXN], path[MAXN][MAXN];

void print(int x, int y)
{
	if(path[x][y] == 1)
	{
		print(x - 1, y - 1);
		putchar(a[x]);
	}
	else if(path[x][y] == 2) print(x - 1, y);
	else if(path[x][y] == 3)print(x, y - 1);
}

int main()
{
	scanf("%s%s", a + 1, b + 1);
	int lena = strlen(a + 1), lenb = strlen(b + 1);
	
	REP(i, 1, lena + 1)
		REP(j, 1, lenb + 1)
		{
			if(a[i] == b[j]) 
			{
				f[i][j] = f[i-1][j-1] + 1;
				path[i][j] = 1;
			}
			else if(f[i-1][j] > f[i][j-1])
			{
				f[i][j] = f[i-1][j];
				path[i][j] = 2;
			}
			else
			{
				f[i][j] = f[i][j-1];
				path[i][j] = 3;
			}
		}
	printf("%d\n", f[lena][lenb]);
	print(lena, lenb);

	return 0;
}

 

posted @ 2018-08-21 19:14  Sugewud  阅读(198)  评论(0编辑  收藏  举报