⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lcs.cpp

📁 这是暑假写的最长公共子序列算法
💻 CPP
字号:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>

#define  MSIZE 100

int  m,n;
char x[100]=" ABCBDAB";
char y[100]=" BDCABA";

int c[MSIZE][MSIZE],b[MSIZE][MSIZE];

void Lcs(){

	int i,j;
	int k=0;
	m=strlen(x);
	n=strlen(y);
    for(i=1;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]==y[j]){
				c[i][j]=c[i-1][j-1]+1;
				b[i][j]=0;
			}
			else if(c[i][j-1]>c[i-1][j]){
				c[i][j]=c[i][j-1];
				b[i][j]=1;
			}
			else{
				c[i][j]=c[i-1][j];
				b[i][j]=2;
			}
		}
}

void Print(int i,int j){

	if(i==0||j==0)
		return;
	if(b[i][j]==0){
		Print(i-1,j-1);
		fflush(stdin);
		printf("%c",x[i]);
	}
	else if (b[i][j]==1)
		Print(i,j-1);
	else Print(i-1,j);

}

void main(){

    printf("x is:%s\n",x);
	printf("y is:%s\n",y);
	Lcs();
	printf("x与y的LCS is:");
	Print(m,n);
	putchar('\n');
	printf("LCS的长度为:%d\n",c[m-1][n-1]);

}


				

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -