Cod sursa(job #2610072)

Utilizator mzzmaraMara-Ioana Nicolae mzzmara Data 4 mai 2020 12:08:51
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.51 kb
#include <bits/stdc++.h> 

const int kNmax = 100005;

struct Edge {
	int x;
	int y;
};

class Task {
 public:
	void solve() {
		read_input();
        get_result();
		print_output();
	}

 private:
	int n;
	int m;
	std::vector<int> adj[kNmax];
    std::vector<std::vector<int>> allBiconexComps;
	std::vector<int> idx;
	std::vector<int> low;
	std::vector<int> parent;
    std::stack<struct Edge> helperStack;

	int time;

	void read_input() {
		std::ifstream fin("biconex.in");
		fin >> n >> m;
		for (int i = 1, x, y; i <= m; i++) {
			fin >> x >> y;
			adj[x].push_back(y);
			adj[y].push_back(x);
		}
		time = 0;
		fin.close();
	}

	void get_result() {
		idx = std::vector<int>(n + 1, 0);
		low = std::vector<int>(n + 1, INT_MIN);
		parent= std::vector<int>(n + 1, -1);
		for (int i = 1; i <= n; i++) {
			if (idx[i] == 0) {
                parent[i] = 0;
				dfsHelper(i);
			}
		}
	}

	void dfsHelper(int node) {
		time++;
		idx[node] = time;
		low[node] = time;
		int numberOfChildren = 0;

        for (auto &adj : adj[node]) {
            if (idx[adj] == 0) {
                struct Edge newEdge;
                newEdge.x = node;
                newEdge.y = adj;
                helperStack.push(newEdge);

                parent[adj] = node;
                numberOfChildren++;

                dfsHelper(adj);
                low[node] = std::min(low[node], low[adj]);

                if (low[adj] >= idx[node]) {
                    getBiconexComp(newEdge);
                }
            } else {
                if (parent[node] != 0) {
					if (adj != parent[node]) {
						low[node] = std::min(low[node], idx[adj]);
					}
                }
            }
        }
	}

    void getBiconexComp(struct Edge &targetEdge) {
        std::set<int> newBiconexComp;
        struct Edge currEdge;

        while (currEdge.x != targetEdge.x || currEdge.y != targetEdge.y) {
            currEdge = helperStack.top();

            newBiconexComp.insert(currEdge.x);
            newBiconexComp.insert(currEdge.y);
            helperStack.pop();
        }

        allBiconexComps.push_back(std::vector<int>(newBiconexComp.begin(), newBiconexComp.end()));
    }

	void print_output() {
		std::ofstream fout("biconex.out");
		fout << allBiconexComps.size() << "\n";
        for (int i = 0; i < allBiconexComps.size(); i++) {
            for (auto& elem : allBiconexComps[i]) {
                fout << elem << " ";
            }
            fout << "\n";
        }
		fout.close();
	}
};

int main() {
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}