Dynamicke programovani:
{compute the lowest badness for the 'Row' characters long row with 'Num' words (Num>2) with a total length of 'Len' (Len<=Row-Num+1)} Function CountBadness (Row, Len, Num: Integer) : Integer; Var SpLen, SpBig: Integer; Begin Dec (Num); {number of spaces between words} SpLen := (Row - Len) div Num; SpBig := (Row - Len) - (SpLen * Num); {now we have Num spaces; 'SpBig' of them are 'SpLen+1' character long; the other are 'SpLen' characters long} CountBadness := (SpLen-1) * (SpLen-1) * (Num - SpBig) + SpLen * SpLen * SpBig; End; { CountBadness } {solve one problem, iterate word by word} Function FindBest (Row: Integer) : Integer; Var I, J, Sum: Integer; Begin For I := 0 to WordCount do Best[I] := -1; Best[0] := 0; For I := 0 to WordCount-1 do If Len[I+1] = Row then Possible (I+1, Best[I]) else Begin Possible (I+1, Best[I] + PENALTY); Sum := Len[I+1]; J := I+1; Repeat Inc (J); Sum := Sum + Len[J]; If (Sum + (J-I-1) <= Row) and (J <= WordCount) then Possible (J, Best[I] + CountBadness (Row, Sum, J-I)); until (Sum + (J-I-1) >= Row) or (J >= WordCount); End; FindBest := Best [WordCount]; End; { FindBest }