首先贴上我的LCS代码:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
const int N = 1000;
const int M = 1000;
class LCS {
public:
/**
* len(x) must be less than M - 1; len(y) must be less than N - 1
*/
LCS(string x, string y);
/**
* Start to Compute
*/
void StartCompute();
void ShowResult();
/**
* Show the mid result
*/
void ShowMidResult();
protected:
string x,y;
int lenx, leny;
int calc[M][N];
int sign[M][N];
};
int main() {
// string x = "ABCBDAB";
// string y = "BDCABA";
string x, y;
cin>>x>>y;
freopen("output.txt", "w", stdout);
LCS a(x, y);
a.StartCompute();
a.ShowResult();
a.ShowMidResult();
}
LCS::LCS(string x, string y) {
this->x = x;
this->y = y;
lenx = x.length();
leny = y.length();
}
void LCS::StartCompute() {
//初始化
for(int i = 0; i <= lenx; i++) {
calc[i][0] = calc[0][i] = 0;
}
//开始计算
for(int i = 1; i <= lenx; i++)
for(int j = 1; j <= leny; j++) {
if(x[i - 1] == y[j - 1]) {
calc[i][j] = calc[i - 1][j - 1] + 1;
sign[i][j] = 0;
}
else if(calc[i - 1][j] < calc[i][j - 1]) {
calc[i][j] = calc[i][j - 1];
sign[i][j] = 1;
}
else {
calc[i][j] = calc[i - 1][j];
sign[i][j] = 2;
}
}
}
void LCS::ShowResult() {
//Show the num of LCS
cout<<"The length of Longest Common Subsequence of x and y:"<<calc[lenx][leny]<<endl;
//Trace back the solution
int lx = lenx;
int ly = leny;
char *c = new char[calc[lenx][leny]];
int lc = calc[lenx][leny] - 1;
while(lx != 0 && ly != 0) {
if(sign[lx][ly] == 0) {
c[lc--] = x[lx - 1];
lx = lx - 1;
ly = ly - 1;
}
else if(sign[lx][ly] == 1) {
ly = ly - 1;
}
else {
lx = lx - 1;
}
}
cout<<"The Longest Common SubSequence: ";
for(int i = 0; i < calc[lenx][leny]; i++) cout<<c[i];
cout<<endl;
}
void LCS::ShowMidResult() {
cout<<"The Auxliary Calculation Matrix :"<<endl;
for(int i = 0 ; i <= lenx; i++) {
for(int j = 0; j <= leny; j++)
cout<<calc[i][j]<<" ";
cout<<endl;
}
cout<<"The notice matrix which for trace back solution:"<<endl;
for(int i = 1; i <= lenx; i++) {
for(int j = 1; j <= leny; j++)
cout<<sign[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}
这段代码在Linux下能够正常编译运行,但是在Windows下 出现错误:
Process is terminated due to stackoverflow.
一开始我以为是系统遭受攻击了.后来发现是因为Windows默认系统栈的大小为1M至2M,我的两个数组设置得过大. 我把M和N的值都设为10, 则程序在Windows下能够正常运行.
Linux下该程序能够正常运行(在不修改的情况下).
http://05240430.blog.163.com/blog/static/133359394201142265850781/
http://superpopb2b.blog.51cto.com/786164/382255
以上是我参照的两篇文章.