D_L3

SDA - test 6 - 2021-2022 - Път в граф

Jan 8th, 2024
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 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 <queue>
  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.  
  39. int main()
  40. {
  41. int n, m, k;
  42. cin >> n >> m;
  43. UnionFind graph(n);
  44.  
  45. long long a, b;
  46.  
  47. for (int i = 0; i < m; i++)
  48. {
  49. cin >> a >> b;
  50. graph.unite(a - 1, b - 1);
  51. }
  52. cin >> k;
  53.  
  54. for (size_t i = 0; i < k; i++)
  55. {
  56. cin >> a >> b;
  57. cout << graph.areInOneSet(a - 1, b - 1) << " ";
  58. }
  59.  
  60. }
  61.  
Advertisement
Add Comment
Please, Sign In to add comment