Cod sursa(job #2348149)

Utilizator ToniBAntonia Biro ToniB Data 19 februarie 2019 13:49:50
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

vector <int> graph[200000 + 5];
vector <int> viz;

void dfs(int nod)
{
    viz[nod] = 1;
    int lim = graph[nod].size();
    for(int i = 0; i < lim; ++i)
    {
        int vecin = graph[nod][i];
        if(viz[vecin] == 0)
            dfs(vecin);
    }
}

int main()
{
    ifstream f("dfs.in");
    ofstream g("dfs.out");
    int n, m;
    f >> n >> m;
    for(int i = 0; i < m; ++i)
    {
        int a, b;
        f >> a >> b;
        graph[a].push_back(b);
        graph[b].push_back(a);
    }

    viz.resize(n+1);
    int s = 0;
    for(int i = 1; i <= n; ++i)
        if(viz[i] == 0)
        {
            dfs(i);
            s++;
        }
    g << s;
    f.close();
    g.close();

    return 0;
}