fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <map>
  4. #include <set>
  5. #include <string>
  6. #include <vector>
  7.  
  8. using namespace std;
  9.  
  10. vector<string> input = {
  11. "a1=a2", "b1=b2", "b3=b2", "c1=c2", "e1=e2", "a3=a4", "c3=c4", "e1=e3",
  12. "a2=a4", "c3=c1", "b3=a4", "c2=d1", "a4=a5", "d2=c1", "b4=b3", "d3=c3"
  13. };
  14.  
  15. int main(void)
  16. {
  17. map<string, int> g;
  18. vector<string> id;
  19.  
  20. for (string &t : input) {
  21. int i = t.find('=');
  22. string a = t.substr(0, i);
  23. string b = t.substr(i + 1);
  24.  
  25. bool hasa = g.find(a) != g.end();
  26. bool hasb = g.find(b) != g.end();
  27.  
  28. if (!hasa) id.push_back(a);
  29. if (!hasb) id.push_back(b);
  30.  
  31. switch (hasa << 1 | hasb) {
  32. case 0:
  33. g[b] = g[a] = g.size();
  34. break;
  35. case 1:
  36. g[a] = g[b];
  37. break;
  38. case 2:
  39. g[b] = g[a];
  40. break;
  41. case 3:
  42. int j = min(g[a], g[b]);
  43. int k = max(g[a], g[b]);
  44. for (auto &x : g) if (x.second == k) x.second = j;
  45. }
  46. }
  47.  
  48. set<int> s;
  49. for (auto &x : g) s.insert(x.second);
  50.  
  51. for (int i : s) {
  52. bool first = true;
  53. for (auto &x : id) if (g[x] == i) cout << (first ? first = false, "[" : ", ") << x;
  54. cout << "]" << endl;
  55. }
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 5312KB
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]