Cod sursa(job #2928779)

Utilizator anca-soranaBalan Anca-Sorana anca-sorana Data 23 octombrie 2022 20:50:29
Problema Componente tare conexe Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.73 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");

int k, n, m, x, y;
stack <int> s;
bool visited[100001] = {false};

void dfs(int i, bool visited[], vector<vector<int>> adjList2, vector <vector<int>> &sol)
{
    visited[i] = true;
    sol[k].push_back(i);

    for(auto j : adjList2[i])
        if(!visited[j])
            dfs(j, visited, adjList2, sol);
}

void order(int j, bool visited[], stack <int> &s, vector<vector<int>> adjList1)
{
    visited[j] = true;
    for(auto i : adjList1[j])
        if(!visited[i])
            order(i, visited, s, adjList1);
    s.push(j);
}

void printCTC(vector<vector<int>> adjList1, vector<vector<int>> adjList2, vector <vector<int>> &sol)
{
    for(int i = 1; i <= n; i++)
        if(!visited[i])
            order(i, visited, s, adjList1);

    for(int i = 1; i <= n; i++)
        visited[i] = false;
    while(!s.empty())
    {
        int a = s.top();
        s.pop();
        if(!visited[a])
        {
            k++;
            dfs(a, visited, adjList2, sol);
        }
    }
}

int main()
{
    f>>n>>m;
    vector <vector <int>> adjList1(n + 1);
    vector <vector <int>> adjList2(n + 1);
    vector <vector<int>> sol(n + 1);
    for(int i = 1; i <= m; i++)
    {
        f>>x>>y;
        adjList1[x].push_back(y);
        adjList2[y].push_back(x);
    }
/*    for(auto i : adjList1)
    {
        for(auto j : i)
            cout<<j<<' ';
        cout<<endl;
    }*/
    printCTC(adjList1, adjList2, sol);

    g<<k<<'\n';
    for(int i = 1; i <= k; i++)
    {
        for(auto j : sol[i])
            g<<j<<' ';
        g<<'\n';
    }
    return 0;
}