Cod sursa(job #1656886)

Utilizator Grigorescu_Nicolae_322CBGrigorescu Nicolae Grigorescu_Nicolae_322CB Data 19 martie 2016 22:39:01
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.89 kb
#include <iostream>
#include <stdio.h>

int N,M,viz[100005], cnt;

typedef struct nod
{
    int val;
    nod * next;
} *pnod;
pnod v[100005];

void add(pnod &x, int v){
    pnod aux;
    aux= new nod;
    aux->val=v;
    aux->next=x;
    x=aux;
}


using namespace std;

void DFS(int x){
    viz[x]=1;
    pnod p=v[x];
    if (p==NULL) return;
    while(p->next!=NULL){
        viz[p->val]=1;
        p=p->next;
    }

}

int main()
{
    FILE *f1,*f2;
    f1=fopen("grader_test1.in","r");
    f2=fopen("grader_test2","w");
    fscanf(f1,"%d %d",&N,&M);
    int i,x,y;
    for (i=0 ;i<M;i++)
    {
        fscanf(f1,"%d %d ",&x,&y);
        add(v[x],y);
        add(v[y],x);
    }
    for (i=1 ;i<N;i++){
        if(!viz[i]){
            cnt++;
            DFS(i);
        }
    }
    fprintf(f2,"%d",cnt);
    fclose(f1);
    fclose(f2);
    return 0;
}