Pagini recente » Cod sursa (job #3184916) | Cod sursa (job #2697297) | Cod sursa (job #316109) | Clasament clasa_9_nationala_2012-2016 | Cod sursa (job #2522289)
#include <bits/stdc++.h>
using namespace std;
int n, m, i, j, x, y, nr_comp, a;
vector <int> G[100005]; //graful implicit
vector <int> GT[100005]; //graful transpus
vector <int> componente[100005];
stack <int> stiva;
bool viz1[100005], viz2[100005];
void dfsG(int x)
{
viz1[x] = true;
for(int i = 0; i < G[x].size();i ++)
{
int aux = G[x][i];
if(viz1[aux] == false)dfsG(aux);
}
stiva.push(x);
}
void dfsGT(int x)
{
viz2[x] = true;
for(int i = 0; i < GT[x].size(); i ++)
{
int aux = GT[x][i];
if(viz2[aux] == false)dfsGT(aux);
}
}
int main()
{
ifstream f("ctc.in");
ofstream g("ctc.out");
f >> n >> m;
for(i = 1; i <= m; i ++)
{
f >> x >> y;
G[x].push_back(y);
GT[y].push_back(x);
}
for(i = 1; i <= n; i ++)
if(viz1[i] == false)dfsG(i);
while(!stiva.empty())
{
int aux = stiva.top();
nr_comp ++;
dfsGT(aux);
while(viz2[a = stiva.top()] == true)
{
componente[nr_comp].push_back(stiva.top());
stiva.pop();
if(stiva.size() == 0)break;
}
}
g << nr_comp << "\n";
for(i = 1; i <= nr_comp; i ++)
{
for(j = 0; j < componente[i].size(); j ++)
g << componente[i][j] << " ";
g << "\n";
}
return 0;
}