Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- class My_Graph {
- public:
- My_Graph(int V, vector<vector<int>> g, vector<vector<int>> t) {
- graph.resize(V);
- trans.resize(V);
- used.resize(V, false);
- help.resize(V);
- for (int i = 0; i < V; i++) {
- graph[i] = g[i];
- trans[i] = t[i];
- }
- }
- ~My_Graph() = default;
- void DFS_1(int vertex);
- void DFS_2(int vertex);
- void Build_Comp();
- int Get_Result();
- private:
- vector<vector<int>> graph;
- vector<vector<int>> trans;
- vector<bool> used;
- vector<int> order;
- vector<int> help;
- vector<vector<int>> components;
- vector<int> component;
- };
- void My_Graph::DFS_1(int vertex) {
- used[vertex] = true;
- for (int i : graph[vertex]) {
- if (!used[i]) {
- DFS_1(i);
- }
- }
- order.push_back(vertex);
- }
- void My_Graph::DFS_2(int vertex) {
- used[vertex] = true;
- component.push_back(vertex);
- for (int i : trans[vertex]) {
- if (!used[i]) {
- DFS_2(i);
- }
- }
- }
- void My_Graph::Build_Comp() {
- used.assign(graph.size(), false);
- for (int i = 0; i < graph.size(); i++) {
- if (!used[i]) {
- DFS_1(i);
- }
- }
- used.assign(graph.size(), false);
- for (int i = 0; i < graph.size(); i++) {
- int temp = order[graph.size() - 1 - i];
- if (!used[temp]) {
- DFS_2(temp);
- for (int j : component) {
- help[j] = components.size();
- }
- components.push_back(component);
- component.clear();
- }
- }
- }
- int My_Graph::Get_Result() {
- Build_Comp();
- int begs = 0;
- int ends = 0;
- bool fl = true;
- for (int i = 0; i < components.size(); i++) {
- for (int v : components[i]) {
- for (int j : graph[v]) {
- if (help[j] != i) {
- fl = false;
- }
- }
- }
- if (fl) begs++;
- fl = true;
- }
- for (int i = 0; i < components.size(); i++) {
- for (int v : components[i]) {
- for (int j : trans[v]) {
- if (help[j] != i) {
- fl = false;
- }
- }
- }
- if (fl) ends++;
- fl = true;
- }
- int res = max(begs, ends);
- if (components.size() == 1) {
- res = 0;
- }
- return res;
- }
- int main() {
- int V = 0;
- int E = 0;
- cin >> V >> E;
- vector<vector<int>> graph;
- vector<vector<int>> trans;
- graph.resize(V);
- trans.resize(V);
- int u = 0;
- int v = 0;
- for (int i = 0; i < E; i++) {
- cin >> u >> v;
- graph[u - 1].push_back(v - 1);
- trans[v - 1].push_back(u - 1);
- }
- My_Graph Graph(V, graph, trans);
- cout << Graph.Get_Result();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement