LCS模板_uva10405

LCS:

  1. i = 0或j = 0, f(i, j) = 0;
  2. f(i, j) = f(i-1, j-1) + 1, a[i] = b[j];
  3. f(i, j) = max(f(i, j-1), f(i-1, j));
#include 
#include 
#include 
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
const int maxn = 1000+5;
int n, m;
char a[maxn], b[maxn];

int d[maxn][maxn];
void lcs(){
	for(int i = 0; i <= max(n,m); ++i) d[i][0] = d[0][i] = 0;
	for(int i = 1; i <= n; ++i){
		for(int j = 1; j <= m; ++j){
			if(a[i] == b[j]) d[i][j] = d[i-1][j-1] + 1;
			else d[i][j] = max(d[i-1][j], d[i][j-1]);
		}
	}
}

int main()
{
	freopen("in.txt","r",stdin);
	
	while(gets(a+1) != NULL){
		gets(b+1);
		n = strlen(a+1);
		m = strlen(b+1);
		lcs();
		printf("%d\n", d[n][m]);
	}
	fclose(stdin);
	return 0;
}


你可能感兴趣的:(动态规划)