Cod sursa(job #1463997)

Utilizator dex4Darjan Catalin dex4 Data 21 iulie 2015 23:52:10
Problema Parcurgere DFS - componente conexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.83 kb
#include <iostream>
#include <vector>
#include <fstream>
#define nmax 10005

using namespace std;

vector<int> G[nmax];
int T[nmax], viz[nmax], head, n, m, x, y, comps;

void build(){
    ifstream f("dfs.in");
    f >> n >> m;
    for(int i=1; i<=n; i++){
        f >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void bfs(int start){
    head = 1;
    viz[start] = 1;
    T[head] = start;
    for(int i=1; i<=head; i++)
        for(int j=0; j<G[T[i]].size(); j++)
            if(!viz[G[T[i]][j]]){
                T[++head] = G[T[i]][j];
                viz[T[head]] = 1;
            }

}

int main()
{
    ofstream g("dfs.out");
    build();
    for(int i=1; i<=n; i++)
        if(!viz[i]){
            bfs(i);
            comps++;
        }
    g << comps;
    return 0;
}