Cod sursa(job #533741)

Utilizator radubbRadu B radubb Data 14 februarie 2011 15:53:19
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <cstdio>
#include <vector>
using namespace std;

#define nmax 100001
vector <long> v[nmax];
vector <long> vt[nmax];
long n, m;
long p_ord[nmax], nr;
bool viz[nmax];


inline void citire()
{
	long x, y;
	freopen("ctc.in","r",stdin); scanf("%ld %ld", &n, &m);
	for(long i=1; i<=m; i++)
	{
		scanf("%ld %ld", &x, &y);
		v[x].push_back(y);
	}
}

void dfst(int x)
{
	viz[x] = false; printf("%ld ", x);
	for(long i=0; i<vt[x].size(); i++)
		if(viz[vt[x][i]])
			dfst(vt[x][i]);
	
}

void dfs(int x)
{
	viz[x] = true;
	for(long i=0; i<v[x].size(); i++)
		if(!viz[v[x][i]])
			dfs(v[x][i]);
	p_ord[++nr] = x;
}

void solve()
{
	long i;
	freopen("ctc.out","w",stdout);
	for(i=1; i<=n; i++)
		if(!viz[i])
			dfs(i);
	
	for(i=1; i<=n; i++)
		for(long j=0; j<v[i].size(); j++)
			vt[ v[i][j] ].push_back(i);

	/*
	for(i=1; i<=n; i++)
	{
		printf("%ld : ", i);
		for(long j=0; j<vt[i].size(); j++)
			printf("%ld ", vt[i][j]);
		printf("\n");
	}
	*/

	for(i=n; i>0; i--)
		if(viz[p_ord[i]])
		{
			dfst(p_ord[i]);
			printf("\n");
		}
}

int main()
{
	citire();
	solve();
	
	return 0;
}