Cod sursa(job #1569229)

Utilizator qwertyuiTudor-Stefan Berbinschi qwertyui Data 15 ianuarie 2016 10:34:14
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream fin ("dfs.in");
ofstream fout ("dfs.out");

typedef struct path {int x; path *y; /*linked path*/} *LinkedPath;
LinkedPath edge[100005];

int visited[100005],n,m;

void add (LinkedPath &source, int DestNode)
{
    LinkedPath temp;
    temp = new path;
    temp->x = DestNode;
    temp->y = source;
    source = temp;
}

void DFS (int node)
{
    LinkedPath temp;
    visited[node]=1;
    for (temp = edge[node]; temp != NULL; temp=temp->y)
        if (!visited[temp->x])
            DFS(temp->x);
}

int main()
{
    int x,y,counter;
    fin >>n >>m;
    for (int i = 1; i <= m; ++i)
    {
        fin >>x >>y;
        add(edge[x],y);
        add(edge[y],x); /* Adds backwards edge*/
    }
    counter = 0;
    for (int i = 1; i <= n; ++i)
        if (!visited[i])
        {
            ++counter;
            DFS(i);
        }
    fout <<counter <<'\n';
    return 0;
}