Cod sursa(job #3255727)

Utilizator StefanRaresStefan Rares StefanRares Data 12 noiembrie 2024 10:32:35
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
const int NMAX = 100001;
int n, m;
bool viz[NMAX];
struct nod
{
    int info;
    nod *urm;
}*v[NMAX];
void adaugareNod(int x, int y)
{
    nod *p = new nod;
    p->info = y;
    p->urm = v[x];
    v[x] = p;
}
void citire()
{
    int x, y;
    f >> n >> m;
    while(m--)
    {
        f >> x >> y;
        adaugareNod(x, y);
        adaugareNod(y, x);
    }
}
void DFS(int x)
{
    viz[x] = 1;
    for(nod *p = v[x]; p != NULL; p = p->urm)
        if(!viz[p->info])
            DFS(p->info);
}
int main()
{
    int nr = 0;
    citire();
    for(int i = 1; i <= n; i++)
        if(!    viz[i])
        {
            nr++;
            DFS(i);
        }
    g << nr;
    f.close();
    g.close();
    return 0;
}