Cod sursa(job #3005154)

Utilizator T1raduTaerel Radu Nicolae T1radu Data 16 martie 2023 19:48:40
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n,m,viz[100001],ctc[100001];
vector<int> G[100001],Gt[100001],f,CC[100001];
void dfs(int x)
{
    viz[x]=1;
    for(vector<int>::iterator it=G[x].begin();it!=G[x].end();it++)
    {
        if(viz[*it]==0)
        {
            dfs(*it);
        }
    }
    f.push_back(x);
}
void dfs_t(int x, int aux)
{
    CC[aux].push_back(x);
    ctc[x]=aux;
    for(vector<int>::iterator it=Gt[x].begin();it!=Gt[x].end();it++)
    {
        if(ctc[*it]==0)
            dfs_t(*it,aux);
    }
}
int main()
{
	fin >> n >> m;
	for(int i=1;i<=m;i++)
    {
        int x,y;
        fin >> x >> y;
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    for(int i=1;i<=n;i++)
    {
        if(viz[i]==0)
            dfs(i);
    }
    int aux=1;
    for(vector<int>::reverse_iterator it=f.rbegin();it!=f.rend();it++)
    {
        if(ctc[*it]==0)
        {
            ctc[*it]=aux;
            dfs_t(*it,aux);
            sort(CC[aux].begin(),CC[aux].end());
            aux++;
        }
    }
    aux--;
    fout << aux << "\n";
    for(int i=1;i<=aux;i++)
    {
        for(vector<int>::iterator it=CC[i].begin();it!=CC[i].end();it++)
            fout << *it << " ";
        fout << "\n";
    }
    return 0;
}