Cod sursa(job #1908052)

Utilizator petardaaaaaAvasiloaie Sebastian petardaaaaa Data 6 martie 2017 22:28:43
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include<fstream>
using namespace std;


ifstream cin("dfs.in");
ofstream cout("dfs.out");

struct nod{
    int val;
    nod *next;
};
bool viz[100005];
int n, m;
nod *l[100005];

void add(int x, int y){
    nod *r, *w;
    r = new nod;    r->val=x;    r->next = NULL;
    w = new nod;    w->val=y;    w->next = NULL;

    if(!l[y]) l[y]=r;
    else{       r->next = l[y];      l[y]=r;}
    if(!l[x]) l[x]=w;
    else{   w->next = l[x];  l[x]=w;}
}

void dfs(int i){
    if(!viz[i]) viz[i]=1;
    while(l[i]!=NULL){
        nod *r; r = l[i]; l[i]=l[i]->next; if(!viz[r->val])   viz[r->val]=1;
    dfs(r->val);
}}

int main(){
    cin>>n>>m;

    while(m--){
        int x, y;
        cin>>x>>y;
        add(x, y);  }
    int comp=0;

    for (int i=1; i<=n; ++i){
        if(viz[i]==0){
            ++comp;
            dfs(i);
        }
    }

    cout<<comp;

    return 0;
}