Cod sursa(job #2850778)

Utilizator CiuiGinjoveanu Dragos Ciui Data 17 februarie 2022 15:46:13
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <queue>
using namespace std;

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

const int MAX_SIZE = 2 * 100005;
vector<int> graph[MAX_SIZE];
int goneThrough[MAX_SIZE];
int totalComponents = 0;

void DFS(int currentPeak) {
    queue<int> positions;
    int ok = 0;
    positions.push(currentPeak);
    if (goneThrough[currentPeak] == 0) {
        goneThrough[currentPeak] = 1;
        ok = 1;
    }
    while (!positions.empty()) {
        int currentPeak = positions.front();
        for (int i = 0; i < graph[currentPeak].size(); ++i) {
            int nextPoint = graph[currentPeak][i];
            if (goneThrough[nextPoint] == 0) {
                positions.push(nextPoint);
                goneThrough[nextPoint] = 1;
            }
        }
        positions.pop();
    }
    if (ok) {
        ++totalComponents;
    }
}

int main() {
    int peaks, arches;
    fin >> peaks >> arches;
    for (int i = 1; i <= arches; ++i) {
        int start, end;
        fin >> start >> end;
        graph[start].push_back(end);
    }
    for (int j = 1; j <= peaks; ++j) {
        DFS(j);
    }
    fout << totalComponents;
    return 0;
}

/*
 Ideea: avem un array pentru a marca daca am trecut deja prin punctul respectiv.
 Ne folosim de o coada pentru a adauga elementele noi.
 Cand coada e goala si daca am parcurs vreun element, adunam cu 1 componentele conexe
 
 */