Cod sursa(job #3370059)

Utilizator hugsfromluizaCroitoru Luiza hugsfromluiza Data 23 octombrie 2026 19:55:23
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n, m, nrc;
bitset<100001> viz;
stack<int> st;
vector<int> l[100001];
vector<int> t[100001];
vector<int> c[100001];
void dfs(int k) {
    viz[k]=1;
    for(auto& v:l[k])
    {
        if(viz[v] == 0)
            dfs(v);
    }
    st.push(k);
}
void dfs_t(int k) {
    viz[k]=1;
    c[nrc].push_back(k);
    for(auto& v:t[k])
    {
        if(viz[v] == 0)
            dfs_t(v);     
    }
}
int main() {
    fin>>n>>m;
    int a,b;
    for(int i=0;i<m;i++)
    {
        fin>>a>>b;
        l[a].push_back(b);
        t[b].push_back(a);
        
    }
    for(int i=1;i<=n;i++)
    {
        if(viz[i] == 0)
            dfs(i);
    }
    viz.reset();
    while(!st.empty())
    {
        int x=st.top();
        st.pop();
        if(viz[x] == 0) {
              dfs_t(x);
              nrc++;   
        }
          
    }
    fout<<nrc<<endl;
    for(int i=0;i<nrc;i++)
    { 
        for(auto& e:c[i])
            fout<<e<<" ";
          fout<<endl;
    }
    return 0;
}