Cod sursa(job #2972615)

Utilizator andreibrosPeta Andrei Mathias andreibros Data 29 ianuarie 2023 20:29:28
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
vector <int> graf1[100005];
vector <int> graf2[100005];
vector <int> ans[100005];
bool viz1[100005];
bool viz2[100005];
vector <int> c;
int sol;
void dfs1(int x)
{
    int y;
    viz1[x]=1;
    for(unsigned int i=0; i<graf1[x].size(); i++)
    {
        y=graf1[x][i];
        if(viz1[y]==0)
            dfs1(y);

    }
    c.push_back(x);
}
void dfs2(int x)
{
    int y;
    viz2[x]=1;
    ans[sol].push_back(x);
      for(unsigned int i=0; i<graf2[x].size(); i++)
      {
          y=graf2[x][i];
          if(viz2[y]==0)
            dfs2(y);
      }
}
int main()
{
    int n,m,x,y;
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y;
        graf1[x].push_back(y);
        graf2[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
        if(viz1[i]==0)
            dfs1(i);

   for( int i=c.size()-1; i>=0; i--)
    {

        if(viz2[c[i]]==0)
        {
            sol++;
            dfs2(c[i]);

        }
    }
    out<<sol<<'\n';

    for(int i=1; i<=sol; i++)
    {
        // afisez componentele din lista i
        for(unsigned int j=0; j<ans[i].size(); j++)
            out<<ans[i][j]<<" ";
        out<<'\n';
    }

    return 0;
}