Cod sursa(job #2833442)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 15 ianuarie 2022 11:05:26
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
int n,m,x,y,component_id;
vector<vector<int>>G,GT,comps;
vector<int>s,component;
vector<bool>vis;
void dfs(int x)
{
    vis[x]=1;
    s.push_back(x);
    for(auto i:G[x])
        if(!vis[i])
            dfs(i);
}
void dfsGT(int x)
{
    vis[x]=1;
    component[x]=component_id;
    for(auto i:GT[x])
        if(!vis[i])
            dfsGT(i);
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    f>>n>>m;
    G=GT=comps=vector<vector<int>>(n+1);
    component=vector<int>(n+1,0);
    vis=vector<bool>(n+1,0);
    for(int i=1; i<=m; i++)
    {
        f>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
        if(!vis[i])
            dfs(i);
    vis=vector<bool>(n+1,0);
    reverse(s.begin(),s.end());
    for(auto it:s)
        if(!vis[it])
        {
            component_id++;
            dfsGT(it);
        }
    g<<component_id<<"\n";
    for(int i=1; i<=n; i++)
        comps[component[i]].push_back(i);
    for(auto it:comps)
    {
        for(auto node:it)
            g<<node<<" ";
        if(it.size())
            g<<"\n";
    }
    return 0;
}