猴子选大王问题 Free Pascal提示202堆栈溢出错type arr=array[1..100000] of longint;var a:arr;i,q,w,s,m,n:longint;procedure du(var m,n,s:longint);begin if s>1 then begin q:=q+1; if a[q]=1 then begin w:=w+1; if w=

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/04 07:54:02
猴子选大王问题 Free Pascal提示202堆栈溢出错type arr=array[1..100000] of longint;var a:arr;i,q,w,s,m,n:longint;procedure du(var m,n,s:longint);begin     if s>1 then     begin     q:=q+1;     if a[q]=1 then     begin     w:=w+1;     if w=

猴子选大王问题 Free Pascal提示202堆栈溢出错type arr=array[1..100000] of longint;var a:arr;i,q,w,s,m,n:longint;procedure du(var m,n,s:longint);begin if s>1 then begin q:=q+1; if a[q]=1 then begin w:=w+1; if w=
猴子选大王问题 Free Pascal提示202堆栈溢出错
type arr=array[1..100000] of longint;
var a:arr;i,q,w,s,m,n:longint;
procedure du(var m,n,s:longint);
begin
if s>1 then
begin
q:=q+1;
if a[q]=1 then
begin
w:=w+1;
if w=n then begin a[q]:=0;w:=0;s:=s-1;end;
end;
if q=m then q:=0;
du(m,n,s);
end;
end;
begin
w:=0;
q:=0;
read(m,n);
s:=m;
for i:= 1 to m do
a[i]:=1 ;
du(m,n,s);
i:=0;
repeat i:=i+1 until a[i]=1;
write(i);
end.



输入的数字小没事 上百的话就出错

猴子选大王问题 Free Pascal提示202堆栈溢出错type arr=array[1..100000] of longint;var a:arr;i,q,w,s,m,n:longint;procedure du(var m,n,s:longint);begin if s>1 then begin q:=q+1; if a[q]=1 then begin w:=w+1; if w=
202是堆栈溢出,就是说系统栈溢出.直接原因是递归深度过大.
你这里s是递归深度,一共使用的堆栈大小是s*(3*4)个byte,而系统提供的栈最大只有640kb,这就是说s最大不能超过91.
解决方法只有改算法,或者不用递归,或者改成人工形式的递归.