Cod sursa(job #3230224)

Utilizator elena_dElena Dulgheru elena_d Data 19 mai 2024 23:52:41
Problema Componente biconexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("biconex.in");
ofstream fout("biconex.out");

#define NMAX 100000

vector<int> graph[NMAX + 2];
int timestamp[NMAX + 2];
int low_link[NMAX + 2];

int nodes_stack[NMAX + 2];
int stack_top;
int comp_cnt;
int timer;

void rst(int n) 
{
    for (int i = 1; i <= n; ++i) {
        low_link[i] = timestamp[i] = 0;
    }
    timer = 0;
    stack_top = 0;
}

void dfs(int node, int parent, bool shouldPrint) {
    timestamp[node] = low_link[node] = ++timer;
    nodes_stack[++stack_top] = node;
    bool art_point = false;

    for (int adjNode : graph[node]) {
        if (adjNode != parent) {
			if (!timestamp[adjNode]) {
				dfs(adjNode, node, shouldPrint);
				low_link[node] = min(low_link[node], low_link[adjNode]);

				if (low_link[adjNode] >= timestamp[node]) {
					art_point = true;
					comp_cnt++;

					if (shouldPrint) {
						fout << "Component " << comp_cnt << ": ";
						while (stack_top > 0 && nodes_stack[stack_top] != adjNode) {
							fout << nodes_stack[stack_top] << " ";
							stack_top--;
						}
						fout << adjNode << " " << node << "\n";
						stack_top--;
					}
				}
			} else {
				low_link[node] = min(low_link[node], timestamp[adjNode]);
			}
		}
    }

    if (!parent && art_point) {
        fout << "Root component: ";
        while (stack_top > 0) {
            fout << nodes_stack[stack_top] << " ";
            stack_top--;
        }
        fout << "\n";
    }
}

int main() {
    int n, m;
    fin >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    dfs(1, 0, false);
    fout << "Number of components: " << comp_cnt << "\n";

    rst(n);
    comp_cnt = 0;
    dfs(1, 0, true);

    fin.close();
    fout.close();
    return 0;
}