Cod sursa(job #2095883)

Utilizator stefdascalescuStefan Dascalescu stefdascalescu Data 28 decembrie 2017 12:58:48
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include<bits/stdc++.h>
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
int n, m, i, j, x, y, nrc, k;
int pls[100002], mns[100002];
vector<int>G[100002], GT[100002], ctc[100002];
stack<int>st;
void dfs1 (int x)
{
    pls[x]=1;
    for (int i=0; i<G[x].size(); i++)
        if (pls[G[x][i]]==0)
            dfs1(G[x][i]);
    st.push(x);
}
void dfs2 (int x)
{
    mns[x]=nrc;
    for (int i=0; i<GT[x].size(); i++)
        if (mns[GT[x][i]]==0)
            dfs2(GT[x][i]);
}
int main ()
{
    f>>n>>m;
    for (i=1; i<=m; i++){
        f>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    for (i=1; i<=n; i++)
        if (pls[i]==0)
            dfs1(i);
    while (!st.empty()){
        k=st.top();
        st.pop();
        if (mns[k]==0){
            nrc++;
            dfs2(k);
        }
    }
    for (i=1; i<=n; i++)
        ctc[mns[i]].push_back(i);
    g<<nrc<<'\n';
    for (i=1; i<=nrc; i++){
        for (j=0; j<ctc[i].size(); j++)
            g<<ctc[i][j]<<" ";
        g<<'\n';
    }
    return 0;
}