Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <unordered_set>
- typedef long long ll;
- using namespace std;
- void CoverComponent(
- ll vertex,
- const vector<unordered_set<ll>>& vertex_to_neighbours,
- vector<bool>& used,
- vector<ll>& vertex_to_component,
- ll component
- )
- {
- used[vertex] = true;
- vertex_to_component[vertex] = component;
- for (auto neighbour : vertex_to_neighbours[vertex]) {
- if (used[neighbour]) {
- continue;
- }
- CoverComponent(
- neighbour,
- vertex_to_neighbours,
- used,
- vertex_to_component,
- component);
- }
- }
- int main() {
- ll number_of_vertices = 0;
- ll number_of_edges = 0;
- cin >> number_of_vertices >> number_of_edges;
- vector<bool> used(number_of_vertices + 1, false);
- vector<unordered_set<ll>> vertex_to_neighbours(number_of_vertices + 1);
- vector<ll> vertex_to_component(number_of_vertices + 1, -1);
- for (ll i = 0; i < number_of_edges; ++i) {
- ll vertex1 = 0;
- ll vertex2 = 0;
- cin >> vertex1 >> vertex2;
- vertex_to_neighbours[vertex1].insert(vertex2);
- vertex_to_neighbours[vertex2].insert(vertex1);
- }
- ll cur_component = 0;
- for (ll vertex = 1; vertex <= number_of_vertices; ++vertex) {
- if (vertex_to_component[vertex] == -1) {
- ++cur_component;
- CoverComponent(
- vertex,
- vertex_to_neighbours,
- used,
- vertex_to_component,
- cur_component);
- }
- }
- cout << cur_component << endl;
- for (ll vertex = 1; vertex <= number_of_vertices; ++vertex) {
- cout << vertex_to_component[vertex] << " ";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment