Georgiy031

Untitled

Apr 6th, 2020
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.63 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. void dfs(int v, int& c, vector<int>& colors, vector<vector<int>>& g) {
  7.     colors[v] = c;
  8.     for (int i = 0; i < g[v].size(); ++i) {
  9.         int to = g[v][i];
  10.         if (colors[to] == 0) {
  11.             dfs(to, c, colors, g);
  12.         }
  13.     }
  14. }
  15. int main() {
  16.     int n, m;
  17.     cin >> n >> m;
  18.     vector<vector<int>> g(n);
  19.     vector<int> colors(n, 0);
  20.     for (int i = 0; i < m; ++i) {
  21.         int a, b;
  22.         cin >> a >> b;
  23.         --a, --b;
  24.         g[a].push_back(b);
  25.         g[b].push_back(a);
  26.     }
  27.     int c = 0;
  28.     for (int i = 0; i < n; ++i) {
  29.         if (colors[i] == 0) {
  30.             dfs(i, ++c, colors, g);
  31.         }
  32.     }
  33.     cout << c << endl;
  34.     for (auto x : colors) cout << x << " ";
  35. }
Add Comment
Please, Sign In to add comment