Cod sursa(job #2192633)

Utilizator PushkinPetolea Cosmin Pushkin Data 6 aprilie 2018 19:17:18
Problema Parcurgere DFS - componente conexe Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 0.87 kb
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
vector<vector<int>> G;
unsigned int n, i, res;
vector<bool> viz;
void rd()
{
    int x, y;
    f>>n>>i;
    viz.resize(n+1);
    G.resize(n+1);
    while(f>>x>>y)
    {
        G[x].push_back(y);
        G[y].push_back(x);
    }
}
queue<int> q;
void BFS(int x)
{
    viz[x]=1;
    q.push(x);
    while(q.size())
    {
        x=q.front();
        q.pop();
        for(i=0;i<G[x].size();i++)
            if(!viz[G[x][i]])
            {
                viz[G[x][i]]=1;
                q.push(G[x][i]);
            }
    }
}
int main()
{
    rd();
    for(i=1;i<=n;i++)
        if(!viz[i])
        {
            BFS(i);
            res++;
        }
    g<<res;
    f.close();
    g.close();
    return 0;
}