Advertisement
KNL

D implementation of kruskals algorithm

KNL
Dec 16th, 2014
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.34 KB | None | 0 0
  1. struct Vertex {
  2.     int number, rank;
  3.     Vertex* parent;
  4.  
  5.     Vertex* find() pure nothrow {
  6.         if (parent != &this)
  7.             parent = parent.find;
  8.         return parent;
  9.     }
  10.  
  11.     void unite(Vertex* x) pure nothrow {
  12.         auto this_root = find;
  13.         auto x_root = x.find;
  14.         if (this_root == x_root)
  15.             this_root.parent = x_root;
  16.         else if (this_root.rank > x_root.rank)
  17.             x_root.parent = this_root;
  18.         else {
  19.             x_root.parent = this_root;
  20.             this_root.rank++;
  21.         }
  22.     }
  23. }
  24.  
  25. void main() {
  26.     import std.stdio, std.typecons, std.conv, std.range,
  27.            std.algorithm, std.string, std.ascii;
  28.  
  29.     auto vertices = new Vertex[readln.strip.to!uint];
  30.     foreach (immutable i, ref v; vertices)
  31.         v = Vertex(i, 0, &v);
  32.     Tuple!(int, uint, uint)[] edges, S;
  33.     foreach (uint i, row; stdin.byLine.map!(r => r.dup).array)
  34.         foreach (uint j, e; row.strip.split(',').to!(int[]))
  35.             if (e != -1)
  36.                 edges ~= tuple(e, i, j);
  37.  
  38.     foreach (const e; edges.schwartzSort!(x => x[0]))
  39.         if (vertices[e[1]].find != vertices[e[2]].find) {
  40.             S ~= e;
  41.             vertices[e[1]].unite(&vertices[e[2]]);
  42.         }
  43.     S.map!(e => e[0]).sum.writeln;
  44.     S.map!(e => [uppercase[e[1]], uppercase[e[2]]]).join(",").writeln;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement