Cod sursa(job #871696)

Utilizator enedumitruene dumitru enedumitru Data 5 februarie 2013 01:13:52
Problema Componente tare conexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream> 
#include <queue> 
#include <bitset> 
#include <vector> 
#define Nmax 5005  
using namespace std; 
ifstream f("ctc.in"); ofstream g("ctc.out");
short n,m,i,j,k,x,y,nrc;
vector <short> G[Nmax],C[Nmax]; 
bitset <Nmax> D[Nmax],viz; 
int main() 
{   f>>n>>m;
	while(m--) 
	{   f>>x>>y; x --, y --; 
		D[x][y] = 1; 
    } 
    /* Construieste matricea drumurilor D prin alg. Roy-Warshall*/
    for(i=0; i<n; ++i) D[i][i] = 1; 
    for(k=0; k<n; ++k)
		for(i=0; i<n; ++i)
			for(j=0; j<n; ++j)
				D[i][j] = D[i][j] | (D[i][k] & D[k][j]); 
    /* Construieste graful pentru determinarea componentelor conexe */
    for (i=0; i<n; ++i) 
		for (j=0; j<n; ++j)
			if(i!=j && (D[i][j] & D[j][i])) 
				G[i].push_back(j), G[j].push_back(i); 
    queue <short> Q;
    for(i=0; i<n; ++i)
	if (!viz[i]) 
	{   viz[i]=1;// parcurgere in latime din varful i
		for(Q.push(i); !Q.empty(); Q.pop()) 
		{   x=Q.front(); 
            C[nrc].push_back(x); 
			vector <short> :: iterator it=G[x].begin(), sf=G[x].end(); 
            for(; it!=sf; ++it) 
                if (viz[*it] == 0) Q.push(*it), viz[*it] = 1; 
        } 
        nrc ++; 
    }
    //afisare componente
    g<<nrc<<"\n"; 
    for (i=0; i<nrc; ++i) 
	{ 	vector <short> :: iterator it=C[i].begin(), sf=C[i].end(); 
        for(; it!=sf; ++it) g<<*it+1<<" "; 
        g << "\n"; 
    } 
    g.close(); return 0; 
}