Cod sursa(job #2487724)

Utilizator Alex_AmarandeiAmarandei Matei Alexandru Alex_Amarandei Data 5 noiembrie 2019 18:15:31
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
#include <vector>
 
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.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;
}