fork download
  1. using static System.Console;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. class Program
  6. {
  7. static void Main()
  8. {
  9. string[] input = {
  10. "a1=a2", "b1=b2", "b3=b2", "c1=c2", "e1=e2", "a3=a4", "c3=c4", "e1=e3",
  11. "a2=a4", "c3=c1", "b3=a4", "c2=d1", "a4=a5", "d2=c1", "b4=b3", "d3=c3"
  12. };
  13.  
  14. var h = new Dictionary<string, int>();
  15.  
  16. foreach (var e in input.Select(s => s.Split('='))) {
  17. var (l, r) = (e[0], e[1]);
  18. switch (h.ContainsKey(l), h.ContainsKey(r)) {
  19. case (false, false):
  20. h[r] = h[l] = h.Count;
  21. break;
  22. case (true, false):
  23. h[r] = h[l];
  24. break;
  25. case (false, true):
  26. h[l] = h[r];
  27. break;
  28. case (true, true):
  29. h.Where(x => x.Value == h[r]).ToList().ForEach(x => h[x.Key] = h[l]);
  30. break;
  31. }
  32. }
  33.  
  34. foreach (var g in h.GroupBy(x => x.Value, x => x.Key)) WriteLine($"[{string.Join(", ", g)}]");
  35. }
  36. }
Success #stdin #stdout 0.05s 28384KB
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]