Cod sursa(job #2222849)

Utilizator stanbianca611Stan Bianca stanbianca611 Data 18 iulie 2018 11:53:58
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
ifstream f ("dfs.in");
ofstream g ("dfs.out");
const int nmax = 100000;
vector<int> v[nmax + 5];
vector<int> viz;
vector<int>::iterator it;
void bfs (int x, int conexe)
{
    queue<int> q;
    int y;
    viz[x]=conexe;
    q.push(x);
    while(!q.empty())
    {
        x=q.front(); q.pop();
        for(it= v[x].begin(); it<v[x].end(); it++)
        {
            y=*it;
            if(!viz[y])
            {
                viz[y]=conexe;
                q.push(y);
            }

        }
    }

}
int main()
{
    int n, m, i, x, y, conexe;
    f>>n>>m;
    for(i=1; i<=m; i++)
    {
        f>>x>>y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    viz.assign(n+1,0);
    conexe=0;
    for(i=1; i<=n; i++)
    {
        if(viz[i]==0)
        {
            conexe++;
            bfs(i, conexe);
        }
    }
    g<<conexe;
    return 0;
}