fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector< int > vis , id;
  4. vector< vector< int > > graph;
  5. void dfs( int node , int cnt)
  6. {
  7. vis[node] = 1;
  8. id[node] = cnt;
  9. for( int u : graph[node] )
  10. {
  11. if( !vis[u] )
  12. dfs(u,cnt);
  13. }
  14. }
  15. int main()
  16. {
  17. int nodes, edges;
  18. cin >> nodes; // input number of nodes in graph
  19. cin >> edges;
  20. vis.resize(nodes+1, 0);
  21. id.resize(nodes+1, 0);
  22. graph.resize(nodes+1);
  23. for( int i = 0 ; i < edges ; i++)
  24. {
  25. int u , v ;
  26. cin >> u >> v;
  27. graph[u].push_back(v); // we can use a pair of (v,cost) in case of weighted graph
  28. graph[v].push_back(u); // if graph is Directed this line will be omitted.
  29. }
  30.  
  31. int cnt = 1 ;
  32. for( int i =1 ; i <= nodes ; i++)
  33. {
  34. if( !vis[i] )
  35. {
  36. dfs(i, cnt++);
  37. }
  38.  
  39. }
  40.  
  41. while(true)
  42. {
  43. int a, b ;
  44. cin >> a >> b;
  45. if( id[a] == id[b] )
  46. cout << "In same connected component\n";
  47. else cout << "In different connected component\n";
  48. }
  49.  
  50. return 0;
  51. }
Runtime error #stdin #stdout #stderr 0s 3472KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::length_error'
  what():  vector::_M_fill_insert