Cod sursa(job #1122774)

Utilizator GhermanGherman Stefan Gherman Data 25 februarie 2014 20:23:12
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.68 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
const int N=100001;
vector<int> a[N];
int n;
bool viz[N];
void citire()
{
    int m,i,x,y;
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
}
void dfs(int x)
{
    viz[x]=true;
    int y;
    for(unsigned i=0;i<a[x].size();i++)
    {
        y=a[x][i];
        if(!viz[y])
            dfs(y);
    }
}
int main()
{
    int nr=0,i;
    citire();
    for (i=1;i<=n;i++)
        if (!viz[i])
        {
            nr++;
            dfs(i);
        }
    g << nr << "\n";
    return 0;
}