石子合并问题的动规解法 pascal 原码

来源:百度知道 编辑:UC知道 时间:2024/06/01 16:00:23

Program Stones;

Type
Node = Record{当前序列的合并方案}
c : Longint;{得分和}
d : Byte{子序列1的堆数}
End;
SumType = Array [1..100,1..100] of Longint;
{sumtype[i,j]-子序列[i,j]的石子总数}
Var
List : Array [1..100,1..100] of Node;
{list[i,j]-子序列[i,j]的合并方案}
Date, Dt : Array [1..100] of Integer;
{Date[i]-第i堆石子数,Dt-暂存Date}
Sum : ^SumType;{sum个[i,j]-指向子序列[i,j]的石子总数的指针}
F : Text;{文件变量}
Fn : String;{文件名串}
N, i, j : Integer;{N-石子堆数,i,j-循环变量}

Procedure Print(i, j : Byte);{递归打印子序列[i,j]的合并过程}
Var
k, x : Shortint;{k-循环变量;x-子序列2中首堆石子的序号}
Begin
If j <> 1 Then Begin{继续倒推合并过程}
Print(i, List[i,j].d);{倒推子序列1的合并过程}
x := (i + List[i, j].d - 1) Mod N + 1;{求子序列2中首堆石子的序号}
Print(x, j - List[i, j].d);{倒推子序列2的合并过程}
For k := 1 to N Do{输出当前合并第i堆,第x堆石子的方案}
If Date[k] > 0 Then Begin
If (i= k)or(x=k)Then Write(F, - Date[k], ' ')
Else Write(F, Date[k], ' ')
End;