Cod sursa(job #1885952)

Utilizator Mihaibv13Mihai Stoian Mihaibv13 Data 20 februarie 2017 16:06:37
Problema Parcurgere DFS - componente conexe Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
vector <int> lv[100010];
vector <int>::iterator it;
int viz[100010];
queue <int> corn;
int n,m,i,x,y;
int kk=1;
int nodnou()
{
    /*int *p;
    p=find(viz+1,viz+n,0);
    if(*p==0) return p-viz;

    return -1;*/
    while(1)
    {
      if (kk==n)
         return -1;

     if(viz[kk++]==0) return kk;
    }
}
int main()
{
    FILE *f=fopen("dfs.in","r");
    FILE *g=fopen("dfs.out","w");

    fscanf(f,"%d%d",&n,&m);
    for(i=1; i<=m; i++)
    {
        fscanf(f,"%d%d",&x,&y);
        lv[x].push_back(y);
        lv[y].push_back(x);
    }
    int nc,cnx=0;
    while(1)
    {
        nc=nodnou();
        if(nc==-1) break;
        cnx++;
        corn.push(nc);
        while(!corn.empty())
        {
            nc=corn.front();
            corn.pop();
            viz[nc]=1;
            for(it=lv[nc].begin(); it!=lv[nc].end(); ++it)
            {
                if(viz[*it]==0) corn.push(*it);
            }


        }




    }
  fprintf(g,"%d",cnx);
    return 0;
}