Cod sursa(job #1125416)

Utilizator alexmarMarinescu Alexandru alexmar Data 26 februarie 2014 17:27:07
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <iostream>
#include<fstream>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
long n,m,nr;
struct nod{
long vec;
nod *urm,*ultim;};
nod *v[100001];
bool ver[100001];
void citire(long x,long y){
    if(!v[x]){
    v[x]=new nod;
    v[x]->vec=y;
    v[x]->urm=NULL;
    v[x]->ultim=v[x];
    }
    else{
    v[x]->ultim->urm=new nod;
    v[x]->ultim=v[x]->ultim->urm;
    v[x]->ultim->vec=y;
    v[x]->ultim->urm=NULL;
    }

}
void dfs(long x){
    ver[x]=1;
    nod *p;p=v[x];
    while(p){
            if(!ver[p->vec])dfs(p->vec);
        p=p->urm;
    }
}
int main()
{
    long i,j,x,y;
    fin>>n>>m;
    for(i=0;i<m;i++){fin>>x>>y;citire(x,y);citire(y,x);}
    for(i=1;i<=n;i++){
        if(!ver[i]){nr++;dfs(i);}
    }
    fout<<nr;
    return 0;
}