Cod sursa(job #3239070)

Utilizator maryyMaria Ciutea maryy Data 2 august 2024 02:47:55
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
const int nmax=1e5;
vector <int> g[nmax+1], gt[nmax+1];
vector <int> comps[nmax+1];
vector <int> component(nmax+1, 0);
vector <int> s;//(nmax+1, 0);//pun nodurile in s in functie de timpul de iesire
bitset <nmax+1> vis;
int n, m;
void dfs(int nod)
{
    if(vis[nod]==0)
    {
        vis[nod]=1;
        for(int i=0; i<g[nod].size(); i++)
        {
            dfs(g[nod][i]);
        }
        s.push_back(nod);
    }
}
void dfsGT(int nod, int component_id)
{
    if(component[nod]==0)
    {
        component[nod]=component_id;
        for(int i=0; i<gt[nod].size(); i++)
        {
            dfsGT(gt[nod][i], component_id);
        }
    }
}
int main()
{
    int x, y;
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
    {
        dfs(i);
    }
    reverse(s.begin(), s.end());
    int component_id=0;
    for(int i=0; i<s.size(); i++)
    {
        if(component[s[i]]==0)
        {
            component_id++;
            dfsGT(s[i], component_id);
        }
    }
    out<<component_id<<'\n';
    for(int i=1; i<=n; i++)
    {
        comps[component[i]].push_back(i);
    }
    for(auto it:comps)
    {
        for(auto nod:it)
        {
            out<<nod<<" ";
        }
        if(it.size()>0)
            out<<'\n';
    }
}