Cod sursa(job #2275687)

Utilizator VanaMarcVana Marc VanaMarc Data 3 noiembrie 2018 13:40:13
Problema Parcurgere DFS - componente conexe Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#include <queue>
using namespace std;

ifstream fi("dfs.in");
ofstream fo("dfs.out");

int n, m, k, r, x, y;
queue <int> Q;

int main()
{
    fi >> n >> m;
    bool A[n + 1][n + 1] = {0};
    int V[n + 1] = {0};
    for (int i = 1; i <= m; ++i)
    {
        fi >> x >> y;
        A[x][y] = 1;
        A[y][x] = 1;
    }
    while (k < n)
    {
        ++ r;
        for (int i = 1; i <= n; ++ i)
            if (V[i]==0)
                Q.push (i), V[i] = r, i = n + 1, ++ k;
        while (!Q.empty ())
        {
            x = Q.front ();
            Q.pop ();
            for (int i = 1; i <= n; ++ i)
            {
                if (V[i] == 0 && A[i][x] == 1)
                {
                    V[i] = r;
                    Q.push (i);
                    ++ k;
                }
            }
        }
    }
  fo<<r;
  fi.close();
  fo.close();
  return 0;
}