Cod sursa(job #1377260)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 5 martie 2015 20:56:31
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int nmax = 100005;

int n, m, x, y, i, cnt, tsort[nmax];

vector<int> v[nmax], g[nmax], s[nmax];
bitset<nmax> viz;

void dfs(int x)
{
    viz[x] = 1;

    for(auto it : v[x])
        if(!viz[it])
            dfs(it);

    tsort[++cnt] = x;
}

void dfst(int x)
{
    viz[x] = 1;
    s[cnt].pb(x);

    for(auto it : g[x])
        if(!viz[it])
            dfst(it);
}

int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);

    scanf("%d%d", &n, &m);

    for(; m; m--)
    {
        scanf("%d%d", &x, &y);
        v[x].pb(y);
        g[y].pb(x);
    }

    for(i = 1; i <= n; i++)
        if(!viz[i])
            dfs(i);

    viz = cnt = 0;
    for(i = n; i; i--)
        if(!viz[tsort[i]])
        {
            cnt++;
            dfst(tsort[i]);
        }

    printf("%d\n", cnt);
    for(i = 1; i <= cnt; i++)
    {
        for(auto it : s[i]) printf("%d ", it);
        printf("\n");
    }

    return 0;
}