Cod sursa(job #3203028)

Utilizator arinaststsArina Stroe arinaststs Data 12 februarie 2024 22:43:30
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m, nrc=1;
vector<int> G[100001], GT[100001], viz(100001);
stack<int> s;
void dfs(int k)
{
    viz[k]=1;
    for(auto i: G[k])
        if(!viz[i])
            dfs(i);
    s.push(k);
}
void dfsGT(int k)
{
    viz[k]=nrc;
    for(auto i: GT[k])
        if(!viz[i])
            dfsGT(i);
}
void citire()
{
    fin>>n>>m;
    for(int i=0; i<m; i++)
    {
        int x, y;
        fin>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}
int main()
{
    citire();
    for(int i=1; i<=n; i++)
        if(!viz[i])
            dfs(i);
    viz=vector<int>(n+1, 0);
    while(!s.empty())
    {
        int x=s.top();
        s.pop();
        if(!viz[x])
            dfsGT(x), nrc++;
    }
    fout<<nrc-1<<'\n';
    for(int i=1; i<nrc; i++)
    {
        for(int j=1; j<=n; j++)
            if(viz[j]==i)
                fout<<j<<" ";
        fout<<'\n';
    }
    return 0;
}