Cod sursa(job #396667)

Utilizator loginLogin Iustin Anca login Data 15 februarie 2010 18:27:33
Problema Componente tare conexe Scor 24
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
# include <fstream>
# include <algorithm>
# include <cstdlib> 
using namespace std;
struct nod {
	int info;
	nod *next;};
nod *g[100004], *gt[100003];
int n, m, final[100003], timp, v[100003], vt[100003], nrc, *ctc[100003];

void add (int i, int j)
{
	nod *q=new nod;
	q->info=j;
	q->next=g[i];
	g[i]=q;
}

void addt (int i, int j)
{
	nod *q=new nod;
	q->info=j;
	q->next=gt[i];
	gt[i]=q;
}

void read ()
{
	ifstream fin ("ctc.in");
	fin>>n>>m;
	for (int i=1;i<=m;i++)
	{
		int x, y;
		fin>>x>>y;
		add (x, y);
		addt (y, x);
	}
}

int cmp (int i, int j)
{
	return ctc[i][1]<ctc[j][1];
	
}

void afis ()
{
	ofstream fout ("ctc.out");
	fout<<nrc<<endl;
	for (int i=1;i<=nrc;i++)
	{
		fout<<ctc[i][0]<<" ";
		for (int j=1;j<=ctc[i][0];j++)
			fout<<ctc[i][j]<<" ";
		fout<<endl;
	}
}

void dfs (int k)
{
	v[k]=1;
	for (nod *p=g[k];p;p=p->next)
		if (!v[p->info])
			dfs(p->info);
	final[++timp]=k;
}

void dfst (int k, int nrc)
{
	vt[k]=nrc;
	ctc[nrc][0]++;
	ctc[nrc]=(int *)realloc (ctc[nrc], (ctc[nrc][0]+1)*4);
	ctc[nrc][ctc[nrc][0]]=k;
	for (nod *p=gt[k];p;p=p->next)
		if (!vt[p->info])
			dfst(p->info, nrc);
}
	

void kosaraju ()
{
	for (int i=1;i<=n;i++)
		if(v[i]==0)
			dfs(i);
	for (int i=timp;i;--i)
		if (vt[final[i]]==0)
		{
			++nrc;
			ctc[nrc]=(int *)malloc (4);
			ctc[nrc][0]=0;
			dfst(final[i], nrc);
		}
}

int main ()
{
	read ();
	kosaraju ();
	afis ();
	return 0;
}