Cod sursa(job #3338777)

Utilizator nverde1119Popa Narcis Constantin nverde1119 Data 4 februarie 2026 23:35:33
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.75 kb
#include <iostream>
#include <fstream>
using namespace std;
const int NMAX = 100001;
int n, m;
struct nod
{
	int vec;
	nod *urm;
};
nod *L[NMAX];
bool viz[NMAX];
ifstream f("dfs.in");
ofstream g("dfs.out");
void adaugare(int x, int y)
{
	nod *p = new nod;
	p->vec = y;
	p->urm = L[x];
	L[x] = p;
}
void citire()
{
	f >> n >> m;
	int x, y;
	for(int i = 1; i <= m; i++)
	{
		f >> x >> y;
		adaugare(x, y);
		adaugare(y, x);
	}
}
void DFS(int i)
{
	viz[i] = 1;
	for(nod *p = L[i]; p != NULL; p = p->urm)
	{
		if(viz[p->vec] == 0)
			DFS(p->vec);
	}
}
int main()
{
	int nr = 0;
	citire();
	for(int i = 1; i <= n; i++)
	{
		if(viz[i] == 0)
		{
			nr++;
			DFS(i);
		}
	}
	g << nr;
	f.close();
	g.close();
	return 0;
}