slen.pas 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const
  2. N = 7;
  3. A : array [1..N,1..N] of word =
  4. ((0, 3, 5, 1, MaxInt,MaxInt,MaxInt),
  5. (MaxInt,0, MaxInt,MaxInt,3, MaxInt,MaxInt),
  6. (MaxInt,2, 0, MaxInt,2, MaxInt,10 ),
  7. (MaxInt,MaxInt,3, 0, MaxInt,3, MaxInt),
  8. (MaxInt,MaxInt,MaxInt,MaxInt,0, MaxInt,2 ),
  9. (MaxInt,MaxInt,MaxInt,MaxInt,7, 0, 9 ),
  10. (MaxInt,MaxInt,MaxInt,MaxInt,MaxInt,MaxInt,0 ));
  11. var
  12. Path : array [0..N-1] of 1..N;
  13. pB,pE : 0..N-1;
  14. Function shortlen(start,en:integer):word;
  15. var
  16. Len : array [1..N] of integer;
  17. From : array [1..N] of 0..N;
  18. Tree : set of 1..N;
  19. cur : 1..N;
  20. i,min : integer;
  21. begin
  22. for i := 1 to N do From[i] := start;
  23. for i := 1 to N do Len[i] := MaxInt;
  24. Len[Start] := 0;
  25. Tree := [];
  26. while true do
  27. begin
  28. min :=MaxInt;
  29. for i := 1 to N do if not (i in Tree) then if Len[i] < min then
  30. begin min := Len[i]; cur := i;end;
  31. if Cur = en then break;
  32. Tree := Tree + [Cur];
  33. for i:= 1 to N do begin
  34. if not (i in Tree) then
  35. if (Len[Cur]+A[Cur,i]) < Len[i] then
  36. begin
  37. From[I] := Cur;
  38. Len[i] := Len[Cur]+A[Cur,i];
  39. end;
  40. end;
  41. end;
  42. ShortLen := Len[en];
  43. repeat
  44. Path[pE] := Cur;
  45. Cur := From[Cur];
  46. inc(pE);
  47. until Cur = start;
  48. Path[pE] := cur;
  49. end;{shortlen}
  50. var
  51. st, en : 1..n;
  52. BEGIN
  53. pE :=1;
  54. sT :=1;
  55. En :=7;
  56. WriteLn('Кратчайшее расстояние от ',sT, ' до ',en,' равно ',ShortLen(st,en));
  57. WriteLn('Путь :');
  58. repeat
  59. WriteLn(Path[pE]);
  60. dec(pE)
  61. until pE = 0;;
  62. END.