zoukankan      html  css  js  c++  java
  • 51nod 最长公共子序列

    基本算法


    如上

    #include <iostream>
    
    using namespace std;
    string a,b;
    int c[1010][1010] = {0};//记忆化最长度
    int step[1010][1010] = {0};//记忆最长来源
    int main()
    {
    	cin>>a>>b;
    	a = '1' + a;
    	b = '1' + b;
    	for(int i = 1; i < b.length() ; i++)
    	{
    		for(int j = 1; j < a.length(); j++)
    		{
    			if(b[i] == a[j])
    			{
    				c[i][j] = c[i - 1][j - 1] + 1;
    				step[i][j] = 1;
    			}
    			else
    			{
    				if(c[i][j - 1] > c[i - 1][j])
    				{
    					c[i][j] = c[i][j - 1];
    					step[i][j] = 2;//左 
    				}
    				else
    				{
    					c[i][j] = c[i - 1][j];
    					step[i][j] = 3;//上 
    				}
    			}
    		}
    	}
    	/*for(int i = 0 ; i < b.length() + 1; i++)
    	{
    		for(int j = 0; j < a.length() + 1; j++)
    		{
    			cout<<step[i][j]<<' ';
    		}
    		cout<<endl<<endl;
    	}*/
    	int x = b.length() - 1,y = a.length() - 1,flag = 0;
    	char ans[1010];
    	while(x != 0 && y != 0)
    	{
    		//cout<<x<<' '<<y<<endl;
    		if(step[x][y] == 1)
    		{
    			ans[flag++] = b[x];
    			//cout<<b[x]<<endl;
    			x--;
    			y--;
    		}
    		else if( step[x][y] == 2)
    		{
    			y--;
    		}
    		else if( step[x][y] == 3)
    		{
    			x--;
    		}
    	}
    	for(int i = flag - 1; i >= 0; i--)
    	{
    		cout<<ans[i];
    	}
    	cout<<endl;
    	return 0; 
    }

  • 相关阅读:
    连续奇数
    50:数根
    38:花生采摘
    素数对
    17:字符串判等
    2702:密码翻译
    27:单词翻转
    15:整理药名
    12:加密的病历单
    09:密码翻译
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270728.html
Copyright © 2011-2022 走看看