fork download
  1. using static System.Console;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. string[] input = {
  6. "a1=a2", "b1=b2", "b3=b2", "c1=c2", "e1=e2", "a3=a4", "c3=c4", "e1=e3",
  7. "a2=a4", "c3=c1", "b3=a4", "c2=d1", "a4=a5", "d2=c1", "b4=b3", "d3=c3"
  8. };
  9.  
  10. var a = new HashSet<string>();
  11. var g = new List<HashSet<string>>();
  12.  
  13. foreach (var h in input.Select(s => s.Split('=').ToHashSet())) {
  14. a.UnionWith(h);
  15. var i = g.Select((x, i) => i).Where(i => g[i].Overlaps(h)).ToArray();
  16. switch (i.Length) {
  17. case 0: g.Add(h); break;
  18. case 1: g[i[0]].UnionWith(h); break;
  19. case 2: g[i[0]].UnionWith(g[i[1]]); g.RemoveAt(i[1]); break;
  20. }
  21. }
  22.  
  23. g.ForEach(x => WriteLine($"[{string.Join(", ", a.Intersect(x))}]"));
Success #stdin #stdout 0.06s 29864KB
stdin
Standard input is empty
stdout
[a1, a2, b1, b2, b3, a3, a4, a5, b4]
[c1, c2, c3, c4, d1, d2, d3]
[e1, e2, e3]