Cod sursa(job #2008707)

Utilizator andreistanStan Andrei andreistan Data 7 august 2017 14:14:22
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
using namespace std;
 
ifstream f("dfs.in");
ofstream g("dfs.out");
int N, M;
bool a[1001][1001], viz[1001];
 
//DFS adancime
 
struct nod
{
    int x;
    nod *leg;
};
nod *v[100001];
 
void add(nod *&dest, int val)
{
    nod *p;
    p = new nod;
    p -> x = val;
    p -> leg = dest;
    dest = p;
}
void citiregraf()
{
    f >> N >> M;
    while(M--)
    {
        int x, y;
        f >> x >> y;
        add(v[x],y);
        add(v[y],x);
    }
}
 
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);
}
 
void componente()
{
    int i, compconex = 0;
    for(i = 1; i <= N; i++)
        viz[i] = 0;
    for(i = 1; i <= N; i++)
        if(viz[i] == 0)
        {
            DFS(i);
            compconex++;
        }
    g << compconex;
}
 
int main()
{
    citiregraf();
    componente();
    return 0;
}