Cod sursa(job #1350652)

Utilizator c0rn1Goran Cornel c0rn1 Data 20 februarie 2015 21:18:15
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
/// kosaraju
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <bitset>
#define NMAX 200008

using namespace std;

int n, m, nrCtc;
int post[NMAX+1];
vector<int> v[NMAX];
vector<int> t[NMAX]; // transp
vector<int> ctc[NMAX];
bitset<NMAX> viz;

void read()
{
   int x, y;
   scanf("%d %d\n", &n, &m);
   for (int i=1; i<=m; ++i){
      scanf("%d %d\n", &x, &y);
      if (find(v[x].begin(), v[x].end(), y) == v[x].end())
         v[x].push_back(y);
      if (find(t[y].begin(), t[y].end(), x) == t[y].end())
         t[y].push_back(x);
   }
}

void dfsNormal(int x)
{
   viz[x] = 1;
   for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it)
      if (!viz[*it])
         dfsNormal(*it);
   post[++post[0]] = x;
}

void dfsTransp(int x)
{
   int y;
   viz[x] = 1;
   ctc[nrCtc].push_back(x);
   for (vector<int>::iterator it = t[x].begin(); it != t[x].end(); ++it){
      y = *it;
      if (!viz[y])
         dfsTransp(y);
   }
}

void kosaraju()
{
   for (int i=1; i<=n; ++i)
      if (!viz[i])
         dfsNormal(i);
   viz = 0;
   for (int i=post[0]; i>=1; --i)
      if (!viz[post[i]]){
         nrCtc++;
         dfsTransp(post[i]);
      }
   printf("%d\n", nrCtc);
   for (int i=1; i<=nrCtc; ++i, printf("\n"))
      for (vector<int>::iterator it = ctc[i].begin(); it != ctc[i].end(); ++it)
         printf("%d ", (*it));
}

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

   return 0;
}