goshansmails

Untitled

Apr 9th, 2020
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <unordered_set>
  4.  
  5. typedef long long ll;
  6.  
  7. using namespace std;
  8.  
  9. void CoverComponent(
  10.     ll vertex,
  11.     const vector<unordered_set<ll>>& vertex_to_neighbours,
  12.     vector<bool>& used,
  13.     vector<ll>& vertex_to_component,
  14.     ll component
  15.         )
  16. {
  17.     used[vertex] = true;
  18.     vertex_to_component[vertex] = component;
  19.     for (auto neighbour : vertex_to_neighbours[vertex]) {
  20.         if (used[neighbour]) {
  21.             continue;
  22.         }
  23.         CoverComponent(
  24.                 neighbour,
  25.                 vertex_to_neighbours,
  26.                 used,
  27.                 vertex_to_component,
  28.                 component);
  29.     }
  30. }
  31.  
  32. int main() {
  33.  
  34.     ll number_of_vertices = 0;
  35.     ll number_of_edges = 0;
  36.     cin >> number_of_vertices >> number_of_edges;
  37.  
  38.     vector<bool> used(number_of_vertices + 1, false);
  39.     vector<unordered_set<ll>> vertex_to_neighbours(number_of_vertices + 1);
  40.     vector<ll> vertex_to_component(number_of_vertices + 1, -1);
  41.  
  42.     for (ll i = 0; i < number_of_edges; ++i) {
  43.         ll vertex1 = 0;
  44.         ll vertex2 = 0;
  45.         cin >> vertex1 >> vertex2;
  46.         vertex_to_neighbours[vertex1].insert(vertex2);
  47.         vertex_to_neighbours[vertex2].insert(vertex1);
  48.     }
  49.  
  50.     ll cur_component = 0;
  51.     for (ll vertex = 1; vertex <= number_of_vertices; ++vertex) {
  52.         if (vertex_to_component[vertex] == -1) {
  53.             ++cur_component;
  54.             CoverComponent(
  55.                     vertex,
  56.                     vertex_to_neighbours,
  57.                     used,
  58.                     vertex_to_component,
  59.                     cur_component);
  60.         }
  61.     }
  62.  
  63.     cout << cur_component << endl;
  64.     for (ll vertex = 1; vertex <= number_of_vertices; ++vertex) {
  65.         cout << vertex_to_component[vertex] << " ";
  66.     }
  67.  
  68.     return 0;
  69. }
Add Comment
Please, Sign In to add comment