binarytrees.pp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. { The Great Computer Language Shootout
  2. http://shootout.alioth.debian.org
  3. contributed by Ales Katona
  4. }
  5. program BinaryTrees;
  6. {$mode objfpc}
  7. type
  8. PNode = ^TNode;
  9. TNode = record
  10. l, r: PNode;
  11. i: Longint;
  12. end;
  13. function CreateNode(l2, r2: PNode; const i2: Longint): PNode;
  14. begin
  15. Result := GetMem(SizeOf(TNode));
  16. Result^.l:=l2;
  17. Result^.r:=r2;
  18. Result^.i:=i2;
  19. end;
  20. procedure DestroyNode(ANode: PNode);
  21. begin
  22. if ANode^.l <> nil then begin
  23. DestroyNode(ANode^.l);
  24. DestroyNode(ANode^.r);
  25. end;
  26. FreeMem(ANode, SizeOf(TNode));
  27. end;
  28. function CheckNode(ANode: PNode): Longint;
  29. begin
  30. if ANode^.l = nil then
  31. Result:=ANode^.i
  32. else
  33. Result:=CheckNode(ANode^.l) + ANode^.i - CheckNode(ANode^.r);
  34. end;
  35. function Make(i, d: Longint): PNode;
  36. begin
  37. if d = 0 then Result:=CreateNode(nil, nil, i)
  38. else Result:=CreateNode(Make(2 * i - 1, d - 1), Make(2 * i, d - 1), i);
  39. end;
  40. const
  41. mind = 4;
  42. var
  43. maxd : Longint = 10;
  44. strd,
  45. iter,
  46. c, d, i : Longint;
  47. tree, llt : PNode;
  48. begin
  49. if ParamCount = 1 then
  50. Val(ParamStr(1), maxd);
  51. if maxd < mind+2 then
  52. maxd := mind + 2;
  53. strd:=maxd + 1;
  54. tree:=Make(0, strd);
  55. Writeln('stretch tree of depth ', strd, #9' check: ', CheckNode(tree));
  56. DestroyNode(tree);
  57. llt:=Make(0, maxd);
  58. d:=mind;
  59. while d <= maxd do begin
  60. iter:=1 shl (maxd - d + mind);
  61. c:=0;
  62. for i:=1 to Iter do begin
  63. tree:=Make(i, d);
  64. c:=c + CheckNode(tree);
  65. DestroyNode(tree);
  66. tree:=Make(-i, d);
  67. c:=c + CheckNode(tree);
  68. DestroyNode(tree);
  69. end;
  70. Writeln(2 * Iter, #9' trees of depth ', d, #9' check: ', c);
  71. Inc(d, 2);
  72. end;
  73. Writeln('long lived tree of depth ', maxd, #9' check: ', CheckNode(llt));
  74. DestroyNode(llt);
  75. end.