Pagini recente » Cod sursa (job #1076578) | Cod sursa (job #859893) | Cod sursa (job #122923) | Cod sursa (job #2052932) | Cod sursa (job #2206949)
#include <iostream>
#include <vector>
#include <fstream>
#define NMAX 100001
/*
Algoritmul lui Kosaraju (Kosaraju - Sharir)
------------------------------------------
Complexitatea este aceea a parcurgerii în adâncime:
= O(n^2) dacă memorăm graful prin matricea de adiacență,
= O(n+m) dacă memorăm graful prin liste de adiacență.
*/
using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
int N, M, nrc;
vector<bool> viz;
vector<int> postordine;
vector<int> v1[NMAX], v2[NMAX], cc[NMAX];
void citiregraf()
{
f >> N >> M;
viz.resize(N + 1, 0);
postordine.resize(N + 1);
while(M--)
{
int x, y;
f >> x >> y;
v1[x].push_back(y);
v2[y].push_back(x);
}
}
void DFS(int vf)
{
viz[vf] = 1;
for(auto &it : v1[vf])
if(viz[it] == 0)
DFS(it);
postordine.push_back(vf);
}
void DFSt(int vf)
{
viz[vf] = 0;
cc[nrc].push_back(vf);
for(auto &it : v2[vf])
if(viz[it] == 1)
DFSt(it);
}
void componente()
{
int i;
for(i = 1; i <= N; i++)
if(viz[i] == 0)
DFS(i);
for(vector<int>::reverse_iterator it = postordine.rbegin() ; it != postordine.rend() ; it++)
if(viz[*it] == 1)
{
nrc++;
DFSt(*it);
}
}
void afis()
{
g << nrc << '\n';
for(int i = 1; i <= nrc; i++)
{
for(auto &it : cc[i])
g << it << ' ';
g << '\n';
}
}
int main()
{
citiregraf();
componente();
afis();
return 0;
}