Cod sursa(job #1634772)

Utilizator zelmoatisTatuta Ionut-Catalin zelmoatis Data 6 martie 2016 14:28:10
Problema Parcurgere DFS - componente conexe Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>
using namespace std;

ifstream f("dfs.in");
ofstream g("dfs.out");
unsigned int n,m;
vector<vector<long long int> >graph;
vector<bool>visited;

void dfs(int vertex)
{if(vertex<0||vertex>n-1)
    return;
stack<int> s;
unsigned int element,i;
bool found;
s.push(vertex);
visited[vertex]=true;
while(!s.empty())
    {element=s.top();
    found=false;
    if(graph[element].size()==0)
        return;
    for(i=0;i<graph[element].size()&&!found;i++)
        {if(!visited[graph[element][i]])
            found=true;
        if(found)
            {
            s.push(graph[element][i]);
            visited[graph[element][i]]=true;
            }
        else
            s.pop();
        }
    }
}


int main()
{f>>n>>m;
graph.resize(n);
visited.resize(n,false);
unsigned int x,y,i;
for(i=0;i<m;i++)
    {
    f>>x>>y;
    x--;
    y--;
    graph[x].push_back(y);
    graph[y].push_back(x);
    }
unsigned int k=0;
for(i=0;i<n&&i<visited.size();i++)
    {if(!visited[i])
        {dfs(i);
        k++;
        }
    }
g<<k;
f.close();
g.close();

return 0;
}