Cod sursa(job #2168277)

Utilizator Alex_AmarandeiAmarandei Matei Alexandru Alex_Amarandei Data 14 martie 2018 10:15:33
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("data.in");
ofstream fout("data.out");

struct node
{
	int x;
	node* next;
};

typedef node* LSI;

int n, m, nr, start = 1;
bool f[100005];

vector <int> v;
LSI a[100005];

void read();
void DFS(int);
void insert(LSI&, int x);

int main()
{
	read();

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

	fout << nr << '\n';

	return 0;
}

void read()
{
	int i, x, y;

	fin >> n >> m;

	for (i = 0; i < m; i++)
	{
		fin >> x >> y;
		insert(a[x], y);
		insert(a[y], x);
	}
}

void DFS(int x)
{
	f[x] = true;

	for (node* p = a[x]; p; p = p->next)
		if (!f[p->x])
			DFS(p->x);
}

void insert(LSI& l, int x)
{
	node *p = new node;

	p->x = x; p->next = l;
	l = p;
}