Cod sursa(job #2363738)

Utilizator noperestayadelin mihoc noperestay Data 3 martie 2019 16:16:45
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <iostream>
#include <fstream>
#include <stdlib.h>
#define lim 1005

using namespace std;

ifstream f("date.in");
ofstream g("date.out");

int n, m, start, viz[lim], compConexe, afis[lim], loc;
int *A[lim];

void DFS(int nod) {
	viz[nod] = 1;
	for (int i = 1; i <= A[nod][i]; i++)
		if (!viz[A[nod][i]])
			DFS(A[nod][i]);
}

int main() {

	f >> n >> m;

	for (int i = 1; i <= n; i++) {
		A[i] = (int *)realloc(A[i], sizeof(int));
		A[i][0] = 0;
	}

	for (int i = 1; i <= m; i++) {
		int x, y;
		f >> x >> y;
		A[x][0]++;
		A[x] = (int *)realloc(A[x], (A[x][0] + 1) * sizeof(int));
		A[x][A[x][0]] = y;
		A[y][0]++;
		A[y] = (int *)realloc(A[y], (A[y][0] + 1) * sizeof(int));
		A[y][A[y][0]] = x;
	}

	/*
	for (int i = 1; i <= n; i++) {
		g << "varful " << i << " are: ";
		for (int j = 1; j <= A[i][0]; j++)
			g << A[i][j] << " ";
		g << "\n";
	}
	*/

	for (int i = 1; i <= n; i++)
		if (!viz[i]) {
			compConexe++;
			DFS(i);
		}

	g << compConexe << "\n";

	return 0;
}