iliya785

Dijkstra O(n^2)

Apr 25th, 2013
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.05 KB | None | 0 0
  1. const
  2.    sz = 5000;
  3.  
  4. var
  5.    g:array[0..sz,0..sz] of longint;
  6.    d:array[0..sz] of int64;
  7.    used:array[0..sz] of boolean;
  8.    i,j,n,m,u,min,s,e:longint;
  9.  
  10. procedure input;
  11. var i,j:longint;
  12. begin
  13.   read(n,s,e);
  14.   for i:=1 to n do
  15.     for j:=1 to n do
  16.       begin
  17.         read(g[i][j]);
  18.         if g[i][j] = -1 then
  19.            g[i][j]:=maxlongint shr 1;
  20.       end;
  21. end;
  22.  
  23. procedure init;
  24. var i:longint;
  25. begin
  26.   for i:=1 to n do
  27.     if i <> s then
  28.        d[i]:=maxlongint;
  29. end;
  30.  
  31. procedure Dijkstra;
  32. var i:longint;
  33. begin
  34.   for i:=1 to n do
  35.     begin
  36.       min:=maxlongint;
  37.       for j:=1 to n do
  38.         if (min > d[j]) and (not used[j]) then
  39.            begin
  40.              min:=d[j];
  41.              u:=j;
  42.            end;
  43.       used[u]:=true;
  44.       for j:=1 to n do
  45.         if (d[j] > d[u] + g[u][j]) and (not used[j]) then
  46.             d[j]:= d[u] + g[u][j];
  47.     end;
  48. end;
  49.  
  50. procedure answer;
  51. begin
  52.   if d[e] < maxlongint shr 1 then
  53.      writeln(d[e])
  54.   else
  55.   writeln(-1);
  56. end;
  57.  
  58. begin
  59.   input;
  60.   init;
  61.   Dijkstra;
  62.   answer;
  63. end.
Advertisement
Add Comment
Please, Sign In to add comment