Cod sursa(job #2020163)

Utilizator nurof3nCioc Alex-Andrei nurof3n Data 9 septembrie 2017 15:03:15
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
using namespace std;
int n, m, viz[100005], cnt;

struct nod
{
    int x;
    nod *leg;
};
nod *v[100001];


void add(nod *&dest, int vf)
{
    nod *p;
    p = new nod;
    p -> x = vf;
    p -> leg = dest;
    dest = p;
}

void citire()
{
    ifstream f("dfs.in");
    f >> n >> m;
    int i, x, y;
    for(i = 1; i <= m; i++)
    {
        f >> x >> y;
        add(v[x], y);
        add(v[y], x);
    }
    f.close();
}

void DFS(int vf)
{
    nod *p;
    viz[vf] = 1;
    for(p = v[vf]; p != NULL; p = p -> leg)
        if(!viz[p -> x]) DFS(p -> x);
}

int main()
{
    ofstream g("dfs.out");
    citire();
    for(int i = 1; i <= n; i++)
        if(!viz[i])
        {
            cnt++;
            DFS(i);
        }
    g << cnt;
    return 0;
}