Cod sursa(job #1913790)

Utilizator zdavid112zIon David-Gabriel zdavid112z Data 8 martie 2017 14:02:49
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

vector<int> rez[100001];
int lrez = 0;
vector<int> g[100001];
vector<int> t[100001];
vector<int> st;
char viz[100001];
int n, m;

void dfs(int n)
{
    if(viz[n] == 0)
        viz[n] = 1;
    else return;
    for(int i = 0; i < g[n].size(); i++)
        dfs(g[n][i]);
    st.push_back(n);
}

void dfst(int n)
{
    if(viz[n] == 1)
        viz[n] = 0;
    else return;
    rez[lrez].push_back(n);
    for(int i = 0; i < t[n].size(); i++)
        dfst(t[n][i]);
}

int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    scanf("%d%d", &n, &m);
    int a, b;
    while(m--)
    {
        scanf("%d%d", &a, &b);
        a--; b--;
        g[a].push_back(b);
        t[b].push_back(a);
    }
    for(int i = 0; i < n; i++)
        if(viz[i] == 0)
            dfs(i);
    for(int i = n - 1; i >= 0; i--)
    {
        if(viz[st[i]] == 1)
        {
            dfst(st[i]);
            lrez++;
        }
    }
    printf("%d\n", lrez);
    for(int i = 0; i < lrez; i++)
    {
        for(int j = 0; j < rez[i].size(); j++)
            printf("%d ", rez[i][j] + 1);
        printf("\n");
    }
    return 0;
}