BÀI 62/2001 - CHÈN XÂU(DÀNH CHO HỌC SINH THCS VÀ PTTH)DO SƠ XUẤT KHI R...

2. Ta không để ý đến ví dụ của đề ra, yêu cầu cần chèn dấu vào giữa các số trong xâu '123456789' để nhận

được kết quả M cho trước.

Sau đây là lời giải của bạn Nguyễn Chí Thức (hiểu theo bài toán 1):

Program Bai62;

Uses crt;

Const fo = 'chenxau.out';

dau: array[1..3] of String[1]= ('', '-', '+');

s:array[1..9] of char=('1','2','3','4','5','6','7','8','9');

Var d:array[1..9] of String[1];

m:longInt;

f:text;

k:integer;

found:boolean;

Procedure Init;

Begin

Write('Cho M=');

Readln(m);

found:=false;

end;

Function tinh(s:string):longint;

Var i,t:longint;

code:integer;

i:=length(s);

While not(s[i] in ['-','+']) and (i>0) do dec(i);

val(copy(s,i+1,length(s)-i),t,code);

If i=0 then begin tinh:=t; exit; end

else

begin

delete(s,i,length(s)-i+1);

If s[i]='+' then tinh:=t+tinh(s);

If s[i]='-' then tinh:=tinh(s)-t;

end;

End;

Procedure Test(i:integer);

Var st:string; j:integer;

st:='';

For j:=1 to i do st:=st+d[j]+s[j];

If Tinh(st) = m then begin writeln(f,st); found:=true; end;

Procedure Try(i:integer);

Var j:integer;

for j:=1 to 3 do

begin

d[i]:=dau[j]; Test(i);

If i<9 then try(i+1);

end;

BEGIN

Clrscr;

Init;

Assign(f,fo);Rewrite(f);

for k:=1 to 2 do

begin

d[1]:=dau[k];

Try(2);

end;

If not found then write(f,'khong co ngiem');

Close(f);

END.

Từ lời giải trên của bạn Thức, để thoả mãn yêu cầu của bài toán 2, trong thủ tục Try cần sửa lại như sau:

d[i]:=dau[j];

If i=9 then Test(i);