Cod sursa(job #1902999)

Utilizator tudor_bonifateTudor Bonifate tudor_bonifate Data 4 martie 2017 21:54:59
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <cstdio>
#include <vector>
using namespace std;
vector <int> G[100005];
vector <int> G1[100005];
vector <int> st;
vector <int> st1;
int nr,i,n,m,x,y,v[100005],v1[100005],crt;
void DFS(int nod)
{
    v[nod]=1;
    for (int i=0; i<G[nod].size(); i++)
        if (!v[G[nod][i]]) DFS(G[nod][i]);
    st.push_back(nod);
}
void DFS1(int nod)
{
    v1[nod]=1;
    for (int i=0; i<G1[nod].size(); i++)
        if (!v1[G1[nod][i]]) DFS1(G1[nod][i]);
    st1.push_back(nod);
}
int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);
    scanf("%d %d",&n,&m);
    for (i=1; i<=m; i++)
    {
        scanf("%d %d",&x,&y);
        G[x].push_back(y);
        G1[y].push_back(x);
    }
    for (i=1; i<=n; i++) v[i]=v1[i]=0;
    for (i=1; i<=n; i++) if (!v[i]) DFS(i);
    nr=0;
    while (!st.empty())
    {
        crt=st[st.size()-1];
        st.pop_back();
        if (!v1[crt])
        {
            DFS1(crt);
            st1.push_back(-1);
            nr++;
        }
    }
    printf("%d\n",nr);
    for (i=0; i<st1.size(); i++)
    {
        if (st1[i]==-1)
        {
            printf("\n");
            continue;
        }
        else printf("%d ",st1[i]);
    }
    return 0;
}