Advertisement
Guest User

C - connect Cities

a guest
Sep 27th, 2020
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define ll long long
  3. #define F(i, n) for (int i = 0; i < n; i++)
  4. using namespace std;
  5. int n, m;
  6. bool a[100 * 100 * 10 + 2];
  7. // map<int, vector<int>> tre;
  8. vector<int> tre[1000*100+5];
  9. void doIT(int i)
  10. {
  11. for (auto x : tre[i])
  12. if (!a[x])
  13. {
  14. doIT(x);
  15. a[x] = true;
  16. }
  17.  
  18. // if (!a[i])
  19. // {
  20. // for (auto x : tre[i])
  21. // doIT(x);
  22. // a[i] = 1;
  23. // }
  24. }
  25. void solve()
  26. {
  27. cin >> n >> m;
  28. int t = m;
  29. for (int i = 0; i <= n; i++)
  30. a[i] = false;
  31. while (t--)
  32. {
  33. int a, b;
  34. cin >> a >> b;
  35. if (tre[a].size() < 1)
  36. {
  37. tre[a] = {b};
  38. }
  39. else
  40. {
  41. tre[a].push_back(b);
  42. }
  43. // if (tre[b].size() < 1)
  44. // {
  45. // tre[b] = {a};
  46. // }
  47. // else
  48. // {
  49. // tre[b].push_back(a);
  50. // }
  51. }
  52. int count = 0;
  53. // for(auto i: tre){
  54. // for(auto x:i.second){
  55. // cout<<i.first<<" ** "<<x<<" ";
  56. // }
  57. // cout<<"|\n#\n";
  58. // }
  59.  
  60. for (int i = 1; i <= n; i++)
  61. {
  62. if (!a[i])
  63. {
  64. doIT(i);
  65. ++count;
  66. // a[i]=1;
  67. }
  68. }
  69. // for (int i = 1; i <= n; i++)
  70. // {
  71. // cout << a[i] << " ";
  72. // }
  73. // cout << "\nanser is :- ";
  74. cout << count - 1;
  75. }
  76. int main()
  77. {
  78. int t = 1;
  79. // cin>>t;
  80. while (t--)
  81. {
  82. solve();
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement