Cod sursa(job #2668606)

Utilizator tudoranita112Tudor Anita tudoranita112 Data 5 noiembrie 2020 03:52:29
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <iostream>
#include <fstream>
using namespace std;

#define NMAX_DFS 100005
int n, m, viz[NMAX_DFS], cnt;

typedef struct nod
{
	int x;
	nod* a;
} *pNod;
pNod v[100005];

void add(pNod& dest, int val)
{
	pNod p;
	p = new nod;
	p->x = val;
	p->a = dest;
	dest = p;
}

void citire()
{
	ifstream dfs_in;
	dfs_in.open("dfs.in");
	

	dfs_in >> n >> m;
	
	int i, x, y;

	for (i = 1; i <= m; i++)
	{
		dfs_in >> x >> y;
		add(v[x], y);
		add(v[y], x);
	}
}

void DFS(int nod)
{
	pNod p;
	viz[nod] = 1;
	for (p = v[nod]; p != NULL; p = p->a) 
		if (!viz[p->x])
			DFS(p->x);
}

void afisare() {
	ofstream dfs_out;
	dfs_out.open("dfs.out");
	dfs_out << cnt;


}


int main()
{
	citire();
	int i;
	for (i = 1; i <= n; i++) if (!viz[i])
	{ 
		cnt++; 
		DFS(i); }
	
	
	afisare();
	
	return 0;
}