Cod sursa(job #2662995)

Utilizator Cioarec_GeorgeCioarec George Cioarec_George Data 25 octombrie 2020 01:05:21
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

vector<int> v[100001], vt[100001], res;
vector<vector<int>> ress;
int n, m;
bool b[100001], bt[100001];
stack<int> s;

void dfs(int node) {
    s.push(node);
    b[node] = true;
    for(int i=0; i<v[node].size(); i++) {
        if(!b[v[node][i]])
            dfs(v[node][i]);
    }
}

void dfst(int node) {
    res.push_back(node);
    bt[node] = true;
    for(int i=0; i<vt[node].size(); i++)
        if(!bt[vt[node][i]])
            dfst(vt[node][i]);
}

int main()
{
    ifstream f("ctc.in");
    ofstream g("ctc.out");
    f>>n>>m;
    for(int i=0; i<m; i++)
    {
        int a1, a2;
        f>>a1>>a2;
        v[a1].push_back(a2);
        vt[a2].push_back(a1);
    }
    for(int i=1; i<=n; i++)
        if(!b[i])
        {
            dfs(i);
            while(!s.empty()) {
                dfst(s.top());
                ress.push_back(res);
                while(!s.empty() && bt[s.top()])
                    s.pop();
                res.clear();
            }
        }
    g<<ress.size()<<endl;
    for(int i=0; i<ress.size(); i++)
    {
        for(int j=0; j<ress[i].size(); j++)
            g<<ress[i][j]<<" ";
        g<<endl;
    }
    return 0;
}