Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <vector>
- #include <cmath>
- #include <algorithm>
- #include <set>
- #include <iostream>
- using namespace std;
- void find_bridges(int v, int last, int self_depth, vector <vector<int>>& gr, vector <int>& depth, vector <int>& min_depth, vector <int>& color, vector <pair<int, int>>& bridges, vector <pair<int,int>> edges) {
- if (color[v] == 2) return;
- int self_min_depth = self_depth;
- depth[v] = self_depth;
- min_depth[v] = self_min_depth;
- color[v] = 1;
- for (int u : gr[v]) {
- if (color[u] == 0) {
- find_bridges(u, v, self_depth + 1, gr, depth, min_depth, color, bridges,edges);
- }
- pair <int, int> ed1 = { min(v,u), max(v,u) };
- pair <int, int> ed2 = { max(v,u), min(v,u) };
- if (u != last || (u == last && count(edges.begin(), edges.end(), ed1) > 1) || (u == last && count(edges.begin(), edges.end(), ed2) > 1)) {
- self_min_depth = min(self_min_depth, min_depth[u]);
- min_depth[v] = self_min_depth;
- if (depth[v] < min_depth[u]) {
- bridges.push_back({ min(v,u), max(v,u) });
- }
- }
- }
- color[v] = 2;
- }
- void components(int v, vector <vector<int>>& gr, vector <int> &color, vector <pair<int, int>> &bridges, vector <int> &This) {
- if (color[v] == 2) return;
- color[v] = 1;
- This.push_back(v);
- for (int u : gr[v]) {
- //проверяем, что это рёбро не мост
- pair <int, int> var1 = { min(v, u), max(v, u) };
- if (find(bridges.begin(), bridges.end(), var1) != bridges.end()) continue;
- pair <int, int> var2 = { max(v,u), min(v, u) };
- if (find(bridges.begin(), bridges.end(), var2) != bridges.end()) continue;
- if (color[u] == 0) {
- components(u, gr, color, bridges, This);
- }
- }
- color[v] = 2;
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- int n, m;
- cin >> n >> m;
- vector <vector<int>> gr(n + 1);
- vector <pair<int, int>> edges;
- for (int i = 1; i < m + 1; ++i) {
- int a, b;
- cin >> a >> b;
- gr[a].push_back(b);
- gr[b].push_back(a);
- edges.push_back({ min(a,b), max(a,b) });
- }
- vector <int> color(n + 1, 0);
- vector <pair<int, int>> bridges;
- vector <int> depth(n + 1, 1e9);
- vector <int> min_depth(n + 1, 1e9);
- for (int i = 1; i <= n; ++i) {
- find_bridges(i, i, 0, gr, depth, min_depth, color, bridges,edges);
- }
- color.assign(n + 1, 0);
- vector <int> This;
- vector <vector <int> > answer;
- for (int i = 1; i <= n; ++i) {
- if (color[i] != 0) continue;
- This.resize(0);
- components(i, gr, color, bridges, This);
- if (This.empty()) continue;
- sort(This.begin(), This.end());
- answer.push_back(This);
- }
- int num = answer.size();
- cout << num << '\n';
- for (auto x : answer) {
- for (auto y : x) cout << y << ' ';
- cout << '\n';
- }cout << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement