Cod sursa(job #1498619)

Utilizator forever16Alex M forever16 Data 8 octombrie 2015 20:49:22
Problema Parcurgere DFS - componente conexe Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 kb
#include <iostream>
#include<fstream>
#include<vector>
#define maxn 200000

using namespace std;
    ifstream in("dfs.in");
    ofstream out("dfs.out");

int n,m,i, x, y, nr=1;
vector<int> v[maxn];
bool viz[maxn];

void dfs(int x)
{   int i;

    for(i=0; i<v[x].size(); i++)
        if(!viz[v[x][i]])
        { viz[v[x][i]]=1;
        dfs(v[x][i]); }

}

int main()
{
    in>>n>>m;
    for(i=1; i<=m; i++)
    {   in>>x>>y;
        v[x].push_back(y);
        v[y].push_back(x);
    }

    dfs(1);
    for(i=1; i<=n; i++)
        if(!viz[i])
        { nr++;
         viz[i]=1;
         dfs(i); }

    out<<nr;
    return 0;
}