Cod sursa(job #2143638)

Utilizator andrei32576Andrei Florea andrei32576 Data 26 februarie 2018 09:48:17
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.65 kb
#include<bits/stdc++.h>
using namespace std;

int n,m,i,x,y,ct;
int s[100002];

vector <int> G[100002];

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

void dfs(int x,int ct)
{
    s[x]=ct;
    unsigned int i;
    for(i=0;i<G[x].size();i++)
        if(s[G[x][i]]==0) dfs(G[x][i],ct);
}

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

    ct=1;
    for(i=1;i<=n;i++)
    {
        if(s[i]==0)
        {
            dfs(i,ct);
            ct++;
        }
    }

    fout<<ct-1;


    fin.close();
    fout.close();
    return 0;
}