zoukankan      html  css  js  c++  java
  • 动态规划方法之最长公共子序列

    问题描述:给定两个序列,找出X和Y的最长公共子序列。

    子问题的递归结构:

    代码:

    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    
    
    #define M	7
    #define N	6
    
    char x[M]={'A','B','C','B','D','A','B'};
    char y[N]={'B','D','C','A','B','A'};
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	cout<<"--------最长公共子序列问题-------"<<endl;
    	int c[M][N],b[M][N];
    	
    	void LCSLength(int m,int n,char *x,char *y,int c[M][N],int b[M][N]);
    	void LCS(int i,int j,char *x,int b[M][N]);
    
    	LCSLength(M,N,x,y,c,b);
    
    	//打印最长公共子序列
    	LCS(M-1,N-1,x,b);			//用到数组的时候警惕是否越界
    	cout<<endl;
    	return 0;
    }
    
    //计算最优值
    void LCSLength(int m,int n,char *x,char *y,int c[M][N],int b[M][N])
    {
    	int i,j;
    	for(i=0;i<m;i++)c[i][0]=0;
    	for(j=0;j<n;j++)c[0][j]=0;
    
    	for(i=0;i<m;i++)
    	{
    		for(j=0;j<n;j++)
    		{
    			if(x[i]==y[j])
    			{
    				c[i][j]=c[i-1][j-1]+1;
    				b[i][j]=1;	//标志而已
    			}
    			else if(c[i-1][j]>=c[i][j-1])
    			{
    				c[i][j]=c[i-1][j];
    				b[i][j]=2;
    			}
    			else
    			{
    				c[i][j]=c[i][j-1];
    				b[i][j]=3;
    			}
    		}
    	}
    }//LCSLength
    
    //构造最优解
    void LCS(int i,int j,char *x,int b[M][N])
    {
    	if(i<0||j<0)return;		//数组下标调整
    	if(b[i][j]==1)
    	{
    		LCS(i-1,j-1,x,b);
    		cout<<x[i];
    	}
    	else if(b[i][j]==2)
    	{
    		LCS(i-1,j,x,b);
    
    	}
    	else
    	{
    		LCS(i,j-1,x,b);
    	}
    }//LCS
    

    测试结果:

    --------最长公共子序列问题-------
    BDAB
    请按任意键继续. . .

  • 相关阅读:
    Model
    暑假集训-计算几何
    暑假集训-字符串
    将博客搬至CSDN
    codeforces #519 A A. Multiplication Table (暴力)
    bc #54 A problem of sorting
    vimrc备份
    codeforces # 317 div 2 B. Order Book(模拟)
    codeforces #317 div2 A. Arrays (水)
    bc #52 div 2 A ||hdoj5417 Victor and Machine (模拟)
  • 原文地址:https://www.cnblogs.com/fistao/p/3132667.html
Copyright © 2011-2022 走看看