一段代码引发的有趣问题

首先贴上我的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

以上是我参照的两篇文章.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值