Cod sursa(job #2168175)

Utilizator vladvlad00Vlad Teodorescu vladvlad00 Data 14 martie 2018 09:53:17
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.77 kb
#include <fstream>

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

struct nod
{
	int x;
	nod *urm;
};

typedef nod* lista;

int n, m, rez, uz[100005];
lista L[100005];

void push(lista &L, int nr);
void DFS(int x);

int main()
{
	int i, x, y;

	fin >> n >> m;
	for (i = 1; i <= m; i++)
	{
		fin >> x >> y;
		push(L[x], y);
		push(L[y], x);
	}
	for (i=1;i<=n;i++)
        if (!uz[i])
        {
            rez++;
            DFS(i);
        }
    fout << rez << '\n';
	return 0;
}

void push(lista &L, int nr)
{
	nod*q = new nod;

	q->x = nr;
	q->urm = L;
	L = q;
}

void DFS(int x)
{
	nod*p;

	//fout << x << ' ';
	uz[x] = 1;
	p = L[x];
	while (p)
	{
		if (!uz[p->x])
			DFS(p->x);
		p = p->urm;
	}
}