Cod sursa(job #3199580)

Utilizator BoggiGurau Bogdan Boggi Data 1 februarie 2024 20:48:50
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

const int MAX_NOD = 100001;
vector<vector<int>> listaAd;
bool vis[MAX_NOD];

void DFS(int nod) {
    for (int i = 0; i < listaAd[nod].size(); ++i) {
        int vecin = listaAd[nod][i];
        if(!vis[vecin]) {
            vis[vecin] = true;
            DFS(vecin);
        }
    }
}

int main()
{
    int nrNod, nrMuc;
    fin >> nrNod >> nrMuc;
    listaAd = vector<vector<int>> (nrNod + 1);
    for (int i = 0; i < nrMuc; ++i) {
        int x, y;
        fin >> x >> y;
        listaAd[x].push_back(y);
    }
    int nrCompCon = 0;
    for (int i = 1; i <= nrNod; ++i) {
        if (!vis[i]) {
            ++nrCompCon;
            DFS(i);
        }
    }
    fout << nrCompCon;
}