Cod sursa(job #2652588)

Utilizator tudorbuhniaTudor Buhnia tudorbuhnia Data 25 septembrie 2020 11:26:41
Problema Parcurgere DFS - componente conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
vector<int> v[100005];
stack<int> s;
bool vs[100005];
void edge(int x,int y)
{
    v[x].push_back(y);
    v[y].push_back(x);
}
void dfs(int n)
{
    int x;
    s.push(n);
    vs[n]=1;
    while(s.empty()==false)
    {
        if(v[n].size()>0)
        {
            x=v[n].back();
            vs[x]=1;
            v[n].pop_back();
            s.push(x);
        }
        else
            s.pop();
    }
}
int main()
{
    ifstream cin("dfs.in");
    ofstream cout("dfs.out");
    int n,m,x,y,res=0;
    cin >> n >> m;
    for(int i=0;i<m;i++)
    {
        cin >> x >> y;
        edge(x,y);
    }
    for(int i=1;i<=n;i++)
    {
        if(vs[i]==0)
        {
            dfs(i);
            res++;
        }
    }
    cout << res;
    return 0;
}