Cod sursa(job #2668012)

Utilizator tudosemihaitudose mihai tudosemihai Data 4 noiembrie 2020 12:20:00
Problema Componente tare conexe Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>

std::ifstream in("ctc.in");
std::ofstream out("ctc.out");

int n, m, ord = 0, count = 0;
bool marked[100005], in_stack[100005];
int order[100005], lowest[100005];
std::vector<int> g[100005], result[100005];
std::stack<int> st;

void tarjan(int node){
    marked[node] = true;
    order[node] = lowest[node] = ++ord;
    st.push(node);
    in_stack[node] = true;
    for(int i = 0; i < g[node].size(); i++) {
        int new_node = g[node][i];
        if (!marked[new_node]) {
            tarjan(new_node);
            lowest[node] = std::min(lowest[node], lowest[new_node]);
        }
        else if(in_stack[new_node]) {
            lowest[node]=std::min(lowest[node],order[new_node]);
        }
    }

    if (lowest[node] == order[node]) {
        int val;
        while (st.top() != node) {
            val = (int) st.top();
            result[count].push_back(val);
            in_stack[val] = false;
            st.pop();
        }
        val = (int) st.top();
        result[count++].push_back(val);
        in_stack[val] = false;
        st.pop();
    }
}

int main() {
    in >> n >> m;
    for (int i = 1; i <= m; i++) {
            int a, b;
            in >> a >> b;
            g[a].push_back(b);
        }
    tarjan(1);
    for(int i = 1; i <= n; i++){
        if(lowest[i] == 0){
            result[count].push_back(i);
            count++;
        }
    }
    out << count << '\n';
    for(int i = 0; i < count; i++){
       for(int j = 0; j < result[i].size(); j++){
           out << result[i][j] << " ";
       }
       out << '\n';
    }

//    std:: cout << "\n\n";
//    for(int i = 1; i <= n; i++)
//        std:: cout << i << " ";
//    std:: cout << "\n";
//    for(int i = 1; i <= n; i++)
//        std:: cout << order[i] << " ";
//    std:: cout << "\n";
//    for(int i = 1; i <= n; i++)
//        std:: cout << lowest[i] << " ";


    return 0;
}