Cod sursa(job #2654037)

Utilizator tudorbuhniaTudor Buhnia tudorbuhnia Data 29 septembrie 2020 18:34:23
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream cin("dfs.in");
ofstream cout("dfs.out");
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,i=0;
    s.push(n);
    vs[n]=1;
    while(s.empty()==false)
    {
        x=s.top();
        if(v[x].size()>0)
        {
            for(i=0;i<v[x].size();i++)
            {
                if(vs[v[x][i]]==0)
                {
                    s.push(v[x][i]);
                    vs[v[x][i]]=1;
                    break;
                }
            }
            if(i==v[x].size())
                s.pop();
        }
        else
            s.pop();
    }
}
int main()
{
    int n,m,x,y,res=0,k;
    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;
}