LCS问题实现---------------(动态规划, 取自算法导论)

本文介绍了一种求解最长公共子序列(LCS)问题的算法实现,并通过具体示例展示了如何使用C++编程语言来找出两个字符串之间的最长公共子序列。该实现采用动态规划方法,能够有效地解决LCS问题。

前面已经参考了几个blog和看了资料,今天自己实现下。

题目以及思想:http://hzzy-010.blog.163.com/blog/static/79692381200872024242126/

#include <iostream>
#include <string>
#include <cstring>


#define maxn 100

using namespace std;

class LCS{
public:
    string ans(const string lft, const string rht);
private:
    string output(const int &m , const int &n, const string &lft, const string &rht);
    int map[maxn][maxn];
    int dir[maxn][maxn];    //0 as not set, 1 pos lft, 2 point to up , 3 other 
};

string LCS::ans(string lft, string rht){        
      memset(map, 0, sizeof(map));
      memset(dir, 0, sizeof(dir));
      for(int i = 1; i <= lft.size(); i++)
        for(int j = 1; j <= rht.size(); j++){
                if(lft[i - 1] == rht[j - 1]){
                        map[i][j] = map[i - 1][j - 1] + 1;
                        dir[i][j] = 3;
                }else if(map[i - 1][j]  > map[i][j -1]){ 
                        map[i][j] = map[i - 1][j];
                        dir[i][j] = 1;
                }else{
                        map[i][j] = map[i][j - 1];
                        dir[i][j] = 2;
                }
        }
       return output(lft.size(), rht.size(), lft, rht); 
}


string LCS::output(const int &m, const int &n, const string &lft, const string &rht){
        //cout << m << n << lft << "  " << rht;
        int x, y;
        x = m, y = n;
        if(x == 0 || y == 0 || !dir[m][n]){
                string ret;
                return ret;
        }else{
                string tmp;
                switch(dir[x][y]){
                    case 1:
                            x--;
                            break;
                    case 2:
                            y--;
                            break;
                    case 3: x--;
                            y--;
                            break;
                }
                if(lft[m - 1] == rht[n - 1]){
                    return output(x, y, lft, rht) + lft[m - 1];
                }else{
                    return output(x, y, lft, rht);
                }
        }
}

int main()
{
    string str1 = "ACCGGTCGAGTGCGCGGAAGCCGGCCGAA";
    string str2 = "GTCGTTCGGAATGCCGTTGCTCTGTAAA";
    LCS test; 
    cout << test.ans(str1, str2) << endl;
return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值