Cod sursa(job #3230471)

Utilizator Edi_GamanGaman Eduard Ionut Edi_Gaman Data 21 mai 2024 18:27:23
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.73 kb
#include <iostream>
#include <fstream>
using namespace std;

struct nod{
    int info;
    nod *leg;
}*G[100005];

bool sel[100005];
ofstream g;

void DFS(int x){
    sel[x]=true;
    for (nod *p=G[x]; p!=NULL; p=p->leg)
        if (!sel[p->info]) DFS(p->info);
}

int main()
{
    long long n, m, x, y;
    nod *p;
    ifstream f ("dfs.in");
    f >> n >> m;
    for (int i=1; i<=m; i++){
        f >> x >> y;
        p=new nod;
        p->info=y;
        p->leg=G[x];
        G[x]=p;
        p=new nod;
        p->info=x;
        p->leg=G[y];
        G[y]=p;
    }
    f.close();
    g.open("dfs.out");
    int nr=0;
    for (int i=1; i<=n; i++)
        if (!sel[i]) {
            nr++;
            DFS(i);
        }
    g << nr;
    g.close();
}