iliya785

Prim O(N^2)

Jun 22nd, 2013
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 0.69 KB | None | 0 0
  1. const
  2.   s = 5001;
  3.  
  4. var
  5.   g:array[0..s,0..s] of longint;
  6.   used:array[0..s] of boolean;
  7.   d:array[0..s] of longint;
  8.   i,j,n,m,u,v,x,y,z,min,mst:longint;
  9.  
  10. begin
  11.   read(n,m);
  12.   for i:=1 to m do
  13.     begin
  14.       read(x,y,z);
  15.       g[x][y]:=z;
  16.       g[y][x]:=z;
  17.     end;
  18.   for i:=2 to n do
  19.     d[i]:=maxlongint;
  20.   for i:=1 to n do
  21.     begin
  22.       min:=maxlongint;
  23.       for j:=1 to n do
  24.         if (d[j] < min) and (not used[j]) then
  25.           begin
  26.             min:=d[j];
  27.             u:=j;
  28.           end;
  29.       used[u]:=true;
  30.       inc(mst,d[u]);
  31.       for j:=1 to n do
  32.         if (d[j] > g[u][j]) and (not used[j]) then
  33.           d[j]:=g[u][j]
  34.     end;
  35.   write(mst);
  36. end.
Advertisement
Add Comment
Please, Sign In to add comment