Cod sursa(job #1464122)

Utilizator dex4Darjan Catalin dex4 Data 22 iulie 2015 13:23:37
Problema Parcurgere DFS - componente conexe Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>
#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;
    memset(T, 0, sizeof(T));
    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;
}