Cod sursa(job #1691102)

Utilizator tiberiu1995Arsene Constantin-Tiberiu tiberiu1995 Data 16 aprilie 2016 21:04:23
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <vector>
#include <stack>
#include <queue>
#include <fstream>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
int n,m,i,j,nr;
vector <vector <int> > graph(100000);
vector <bool> visited (100000,false);
void dfs(int vertex)
{   if(vertex<0||vertex>n-1)
        return;
    stack <int> s;
    int element,i;
    bool found;
    s.push(vertex);
    visited[vertex]=true;
    //cout<<vertex+1<<" ";
    while(!s.empty())
    {   element=s.top();
        found=false;
        for(i=0;i<graph[element].size()&&(!found);i++)
            if(!visited[graph[element][i]])
                found=true;
        if(found)
        {   i--;
            s.push(graph[element][i]);
            //cout<<graph[element][i]+1<<" ";
            visited[graph[element][i]]=true;
        }
        else s.pop();
    }
}
int main()
{   int x,y,s;
    f>>n>>m;
    for(i=0;i<m;i++)
    {   f>>x>>y;
        x--; y--;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }
    for(i=0;i<n;i++)
        if(!visited[i])
        {   nr++;
            dfs(i);
        }
    g<<nr;
    return 0;
}