Cod sursa(job #3235204)

Utilizator Sasha_12454Eric Paturan Sasha_12454 Data 16 iunie 2024 11:02:08
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <bits/stdc++.h>

std :: ifstream in ("dfs.in");

std :: ofstream out ("dfs.out");

const int NMAX = 1e5 + 5;

int n;

int m;

int x;

int y;

std :: vector <int> v[NMAX];

bool ok;

bool visited[NMAX];

std :: stack <int> s;

int cnt;

void fil()
{
    while(!s.empty())
    {
        int nod = s.top();
        s.pop();

        for(int i : v[nod])
        {
            if(!visited[i])
            {
                visited[i] = true;
                s.push(i);
            }
        }
    }
}

int main()
{

    in >> n >> m;

    for(int i = 1; i <= m; i ++)
    {

        ok = true;

        in >> x >> y;

        for(int i : v[x])
        {
            if(i == y)
            {
                ok = false;
            }
        }

        if(ok)
        {
            v[x].push_back(y);
            v[y].push_back(x);
        }
    }

    for(int i = 1; i <= n; i ++)
    {
        if(!visited[i])
        {
            visited[i] = true;
            cnt ++;
            s.push(i);
            fil();
        }
    }

    out << cnt;

    return 0;
}