Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct Vertex {
- int number, rank;
- Vertex* parent;
- Vertex* find() pure nothrow {
- if (parent != &this)
- parent = parent.find;
- return parent;
- }
- void unite(Vertex* x) pure nothrow {
- auto this_root = find;
- auto x_root = x.find;
- if (this_root == x_root)
- this_root.parent = x_root;
- else if (this_root.rank > x_root.rank)
- x_root.parent = this_root;
- else {
- x_root.parent = this_root;
- this_root.rank++;
- }
- }
- }
- void main() {
- import std.stdio, std.typecons, std.conv, std.range,
- std.algorithm, std.string, std.ascii;
- auto vertices = new Vertex[readln.strip.to!uint];
- foreach (immutable i, ref v; vertices)
- v = Vertex(i, 0, &v);
- Tuple!(int, uint, uint)[] edges, S;
- foreach (uint i, row; stdin.byLine.map!(r => r.dup).array)
- foreach (uint j, e; row.strip.split(',').to!(int[]))
- if (e != -1)
- edges ~= tuple(e, i, j);
- foreach (const e; edges.schwartzSort!(x => x[0]))
- if (vertices[e[1]].find != vertices[e[2]].find) {
- S ~= e;
- vertices[e[1]].unite(&vertices[e[2]]);
- }
- S.map!(e => e[0]).sum.writeln;
- S.map!(e => [uppercase[e[1]], uppercase[e[2]]]).join(",").writeln;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement