Pagini recente » Cod sursa (job #2465620) | Cod sursa (job #188484) | Cod sursa (job #2975985) | Cod sursa (job #1364334) | Cod sursa (job #2924728)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
const int NMAX = 1.0e5 + 5;
bool Belonging[NMAX], Seen[NMAX];
vector < int > Edges[NMAX];
vector < vector < int > > Components;
stack < int > Q;
int NodeLevel[NMAX], RootLevel[NMAX], nrCMP = -1, Level, N, M;
void Tarjan(int x)
{
Level++;
NodeLevel[x] = RootLevel[x] = Level;
Seen[x] = 1;
Belonging[x] = 1;
Q.push(x);
for(int newX : Edges[x])
{
if(!Seen[newX])
{
Tarjan(newX);
RootLevel[x] = min(RootLevel[x], RootLevel[newX]);
}
else
{
if(Belonging[newX])
RootLevel[x] = min(RootLevel[x], RootLevel[newX]);
}
}
if(NodeLevel[x] == RootLevel[x])
{
int Node;
nrCMP++;
Components.push_back(vector < int > ());
do
{
Node = Q.top();
Q.pop();
Components[nrCMP].push_back(Node);
Belonging[Node] = 0;
} while (Node != x);
}
}
int main()
{
int x, y;
in >> N >> M;
for(int i = 1; i <= M; i++)
{
in >> x >> y;
Edges[x].push_back(y);
}
for(int i = 1; i <= N; i++)
{
if(!Seen[i])
{
Level = 0;
Tarjan(i);
}
}
for(vector < int > it : Components)
{
for(int x : it)
out << x << ' ';
out << '\n';
}
return 0;
}