ink; End;<Var> Solution:Array[1..1000] of Link; (对于a^n的所有可能解) Cost :Array[1..1000] of Integer; (解的代价) max :Integer; (推算的上界)<Main Program>Procedure GetSolution;Var i,j :Integer; min,c:Integer; count:Integer; temp,tail
ink; plan :Array[1..500] of Integer; nUsed:Array[1..1000] of Boolean; Procedure GetCost(From,Cost:Integer); (搜索计算最优解) Var temp
ink; a,b :Boolean; i :Integer; Begin If Cost>c then Exit; (剪枝) If From=1 then (递归终结条件) Begin If Cost<c then c:=Cost; Exit; End; temp:=Solution[From]; While temp<>NIL do (搜索主体) Begin a:=nUsed[temp^.Split]; If not a then inc(cost); nUsed[temp^.Split]:=True; b:=nUsed[From - temp^.Split]; If not b then inc(cost); nUsed[From-temp^.Split]:=True; i:=From-1; While (i>1) and (not nUsed) do dec(i); GetCost(i,Cost); If not a then dec(cost); If not b then dec(cost); nUsed[From-temp^.Split]:=b; nUsed[temp^.Split]:=a; temp:=temp^.next; End; End;Begin For i:=2 to Max do(动态规划计算所有解) Begin count:=0; min:=32767; For j:=1 to i div 2 do (将I分解为I-J和J) Begin c:=32767; FillChar(nUsed,Sizeof(nUsed),0); nUsed[j]:=True;nUsed[i-j]:=True; If j=i-j then GetCost(i-j,1) Else GetCost(i-j,2); If c<min then Begin count:=1; min:=c; plan[count]:=j; End Else if c=min then Begin inc(count); plan[count]:=j; End; End; new(solution); (构造解答链表) solution^.split:=plan[1]; solution^.next:=NIL; Cost:=min; tail:=solution; For j:=2 to count do Begin new(temp); temp^.split:=plan[j]; temp^.next:=NIL; tail^.next:=temp; tail:=temp; End; End;End;| 欢迎光临 华师一附中OI组 (http://hsyit.cn/) | Powered by Discuz! X3.2 |