【动态规划】求最大公共子序列

算法没搞好啊!!

#include<iostream>
#include<string>
using namespace std;
const int MAX = 100; 

void LCSLength(string x, string y, int xlen, int ylen, int c[][MAX], int b[][MAX])
{
	int i, j;
	for(i = 0; i <= xlen ; i++)
	    c[i][0] = 0;
	for(j = 0; j <= ylen ; j++)
	    c[0][j] = 0;
	for(i = 1; i <= xlen ; i++){
		for(j = 1 ; j <= ylen ; 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(string x, int b[][MAX], int i, int j)
{
	if(i == 0 || j == 0)
	   return;
	if(b[i][j] == 0){
		// cout<< x[i-1] <<' '; //逆序输出 
		PrintLCS(x, b, i-1, j-1);
		cout<< x[i-1] <<' ';//注意次序 ,顺序输出 
	}
	else if(b[i][j] == 1){
		PrintLCS(x, b, i-1, j);
	}
	else{
		PrintLCS(x, b, i, j-1);
	}
}

int main()
{
	string x = "abcdefggigk" ;
	string y = "acdefhglkm" ;
	int xlen = x.length();
	int ylen = y.length();
	int b[MAX][MAX];
	int c[MAX][MAX];
	LCSLength(x, y, xlen, ylen, c, b);
    PrintLCS(x,b,xlen,ylen);
   	cout<<endl;
}

猜你喜欢

转载自blog.csdn.net/yiyao8236/article/details/79949256