Advertisement
momo2345

Graph Connectivity

May 26th, 2023
518
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. #define suni ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0)
  4. #define ll long long
  5. //#define tc int tc;cin>>tc;while(tc--)
  6. #define pb push_back
  7. #define endl "\n"
  8. #define spc " "
  9. #define yes "YES"
  10. #define no "NO"
  11. #define loop for(int i=0;i<n;i++) cin>>a[i]
  12. #define loop1 for(int i=0;i<n;i++) cin>>b[i]
  13. #define loop2 for(ll i=0;i<n;i++) cin>>c[i]
  14. #define beg begin()
  15. #define en end()
  16. // for determining positions// lower_bound( arr.begin(), arr.end(), ele)- arr.begin();
  17. // for determining positions// upper_bound( arr.begin(), arr.end(), ele)- arr.begin();
  18. // for finding elements //  binary_search(arr.begin(), arr.end(), ele);
  19. // for sorting in vector// sort(a.begin(), a.end());
  20.  vector<int>adj[1000090];
  21. void dfs (int node, vector<bool>&visited)
  22. {
  23.     visited[node] = true;
  24.     for(int i =0; i<adj[node].size(); i++)
  25.     {
  26.         if( visited[adj[node][i]] == false)
  27.         {
  28.             dfs(adj[node][i], visited);
  29.         }
  30.     }
  31. }
  32. int main()
  33. {
  34.   suni;
  35.   char c, a, b;
  36.    int tc; cin>>tc;
  37.    while(tc--){
  38.     int nodes ;
  39.     cin>>c;
  40.     nodes = c - '0' - 16;
  41.     cin.ignore();
  42.     string s;
  43.     while(getline(cin, s) && s!= "")
  44.     {
  45.        adj[s[0] - '0'- 16].push_back(s[1]-'0' - 16);
  46.        adj[s[1] - '0' - 16].push_back(s[0] - '0' - 16);
  47. }
  48. vector<bool>visited(nodes+1, false);
  49.     int conn = 0;
  50.     for(int i =1; i<= nodes; i++)
  51.     {
  52.        if(! visited[i]){
  53.             conn++;
  54.             dfs(i, visited);
  55. }
  56. }
  57. cout<<conn<<endl;
  58.  if(tc) cout<<endl;
  59.    for(int i =1; i<=nodes; i++) adj[i].clear();
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement