Cod sursa(job #1844095)

Utilizator igroitaGroita Igor igroita Data 9 ianuarie 2017 18:43:10
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
#include<fstream>
 
using namespace std;

ifstream cin("dfs.in");
ofstream cout("dfs.out");
 
int n, m, viz[100005], cnt=0;

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 DFS(int nod)
{
    pNod p;
    viz[nod] = 1;
    for (p = v[nod]; p != NULL; p = p -> a) if (!viz[p -> x]) DFS(p -> x);
}   
 
int main()
{
    cin>>n>>m;
    int x, y;
    for(int i=0; i<m; ++i){
    	cin>>x>>y; 
		add(v[x], y);
    	add(v[y],x);
	}
    
    int i;
    for (i = 1; i <= n; i++) if (!viz[i]) { cnt++; DFS(i);}
	cout<<cnt;
    return 0;
}