南郵《算法設計與分析》動態規劃源碼

#include<stdio.h>
#include<iostream.h>
#include<string.h>
#define maxlength 11

class LCS
{
public:
	LCS(int nx,int ny,char *x,char *y)
	{
		m=nx;
		n=ny;
		a=new char[m+2];
		b=new char[n+2];
		memset(a,0,m+2);
		memset(b,0,n+2);
		a[0]='0';
		b[0]='0';
		for(int i=1;i<m+2;i++)
			a[i]=x[i-1];
		for( i=1;i<n+2;i++)
			b[i]=y[i-1];
		c=new int[maxlength][maxlength];
		s=new int[maxlength][maxlength];
		for(i=0;i<maxlength;i++)
			for(int j=0;j<maxlength;j++)
			{
				c[i][j]=0;
				s[i][j]=0;
			}
	
	}
	int LCSLength();
	void CLCS()
	{
		CLCS(m,n);
	}
private:
	void CLCS(int i,int j) const;
	int(*c)[maxlength],(*s)[maxlength];
	int m,n;
	char *a,*b;
};


int LCS::LCSLength()
{
	for(int i=0;i<=m;i++)
		c[i][0]=0;
	for(int j=1;j<=n;j++)
		c[0][j]=0;
	for(i=1;i<=m;i++)
		for(j=1;j<=n;j++)
			if(a[i]==b[j])
			{
				c[i][j]=c[i-1][j-1]+1;
				s[i][j]=1;
			}
			else
				if(c[i-1][j]>=c[i][j-1])
				{
					c[i][j]=c[i-1][j];
					s[i][j]=2;
				}
				else
				{
					c[i][j]=c[i][j-1];
					s[i][j]=3;
				}
	return c[m][n];
}

void LCS::CLCS(int i,int j)const
{
	if(i==0||j==0) return;
	if(s[i][j]==1)
	{
		CLCS(i-1,j-1);
		cout<<a[i];
	}
	else
		if(s[i][j]==2) CLCS(i-1,j);
		else CLCS(i,j-1);
}


void main()
{
	int nx,ny;
	char *x,*y;
	nx=7;
	ny=6;
	x="abcbdab";
	y="bdcaba";
	LCS lcs(nx,ny,x,y);
	lcs.LCSLength();
	lcs.CLCS();
	cout<<endl;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章