Cod sursa(job #1666080)

Utilizator tudormaximTudor Maxim tudormaxim Data 27 martie 2016 17:26:40
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
using namespace std;

ifstream f ("dfs.in");
ofstream fout ("dfs.out");

const int nmax = 1e5+5;
const int bmax = 1<<19;
vector <int> g[nmax];
bitset <nmax> viz;
int poz=bmax-1;
char buff[bmax];

class scanner{
public:
    inline scanner& operator >> (int &val){
        while(!(buff[poz]>='0' && buff[poz]<='9'))
            if(++poz==bmax) f.read(buff, bmax), poz=0;
        val=0;
        while(buff[poz]>='0' && buff[poz]<='9'){
            val=(val<<1)+(val<<3)+buff[poz]-'0';
            if(++poz==bmax) f.read(buff, bmax), poz=0;
        }
        return *this;
    }
}fin;

void dfs(int dad){
    vector <int> :: iterator son;
    viz[dad]=true;
    for(son=g[dad].begin(); son!=g[dad].end(); son++)
        if(viz[*son]==false) dfs(*son);
}

int main(){
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y, nr=0;
    fin >> n >> m;
    while(m--){
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    for(i=1; i<=n; i++)
        if(viz[i]==false) nr++, dfs(i);
    fout << nr;
    f.close();
    fout.close();
    return 0;
}