D_L3

SDA - test 6 - 2021-2022 - Преброяване на области

Jan 8th, 2024
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <vector>
  5. #include <iostream>
  6. #include <algorithm>
  7. #include <unordered_map>
  8. #include <set>
  9.  
  10. using namespace std;
  11.  
  12. struct UnionFind {
  13. vector<int> parents;
  14. public:
  15. UnionFind(int count) : parents(count) {
  16. for (int i = 0; i < count; i++)
  17. {
  18. parents[i] = i;
  19. }
  20. }
  21. bool areInOneSet(int a, int b) {
  22. return getParent(a) == getParent(b);
  23. }
  24.  
  25. int getParent(int idx) {
  26. if (parents[idx] == idx)
  27. {
  28. return idx;
  29. }
  30.  
  31. return parents[idx] = getParent(parents[idx]);
  32. }
  33.  
  34. void unite(int a, int b) {
  35. parents[getParent(a)] = getParent(b);
  36. }
  37.  
  38. int countUniqueParents() {
  39. set<int> unique;
  40.  
  41. for (size_t i = 0; i < parents.size(); i++)
  42. {
  43. unique.insert(parents[i] = getParent(i));
  44. }
  45. return unique.size();
  46. }
  47. };
  48.  
  49. int main()
  50. {
  51. int t, x, y, a, b;
  52.  
  53. cin >> t;
  54.  
  55. vector<int> results;
  56.  
  57. for (size_t i = 0; i < t; i++)
  58. {
  59. cin >> x >> y;
  60. UnionFind graph(x);
  61. for (size_t j = 0; j < y; j++)
  62. {
  63. cin >> a >> b;
  64. graph.unite(a, b);
  65. }
  66. results.push_back(graph.countUniqueParents());
  67. }
  68.  
  69. for (auto num : results) {
  70. cout << num << " ";
  71. }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment