Cod sursa(job #2796817)

Utilizator realmeabefirhuja petru realmeabefir Data 8 noiembrie 2021 20:28:04
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

class graph
{
public:
    void bfs();
    ///////////////////////////////////////////////////////////
    void _dfs_rec(int s, int viz[], vector<int> la[]);
    void dfs();
};

void graph::bfs()
{
    ifstream f("bfs.in");
    ofstream g("bfs.out");
    int n,m,s;
    vector<int>* la = new vector<int>[100005];
    int* dist = new int[100005];

    f >> n >> m >> s;
    memset(dist, -1, sizeof(int) * (n+1));
    for (int i = 1; i <= m; i++)
    {
        int x,y;
        f >> x >> y;
        la[x].push_back(y);
    }

    int curr_dist = 1;
    queue<int> q;
    q.push(s);
    dist[s] = 0;

    while (q.size())
    {
        for (auto& v: la[q.front()])
        {
            if (dist[v] == -1)
            {
                dist[v] = dist[q.front()] + 1;
                q.push(v);
            }
        }
        q.pop();
    }

    for (int i = 1; i <= n; i++)
        g << dist[i] << ' ';

    delete[] dist;
    delete[] la;
}

void graph::_dfs_rec(int s, int viz[], vector<int> la[])
{
    viz[s] = 1;
    for (auto& el: la[s])
    {
        if (viz[el] == 0)
            _dfs_rec(el, viz, la);
    }
}

void graph::dfs()
{
    ifstream f("dfs.in");
    ofstream g("dfs.out");
    int n,m;
    vector<int>* la = new vector<int>[100005];
    int* viz = new int[100005];

    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x,y;
        f >> x >> y;
        la[x].push_back(y);
        la[y].push_back(x);
    }

    int cc = 0;
    for (int i = 1; i <= n; i++)
    {
        if (viz[i] == 0)
        {
            _dfs_rec(i, viz, la);
            cc++;
        }
    }

    g << cc;

    delete[] viz;
    delete[] la;
}

int main()
{
    graph g;
    g.dfs();

    return 0;
}