Cod sursa(job #772048)

Utilizator NexflameGeorge Pultea Nexflame Data 28 iulie 2012 00:24:24
Problema Parcurgere DFS - componente conexe Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

struct dfs
{
    vector<int> urmasi;
    bool vizitat;

};

dfs* vi;

void adauga(long a, long b)
{
    vi[a].urmasi.push_back(b);
}

void depth(long a)
{
    if (vi[a].vizitat)
        return;

    for (long i = 0; i < vi[a].urmasi.size(); i++)
        depth(vi[a].urmasi.at(i));

    vi[a].vizitat = true;
}

int main()
{
    ifstream in("dfs.in");
    ofstream out("dfs.out");

    long n, m;

    in >> n >> m;

    vi = new dfs[n];

    for (long i = 0; i < n; i++)
        vi[i].vizitat = false;

    for (long i = 0; i < m; i++)
    {
        long unde, pecine;
        in >> unde >> pecine;
        --unde, --pecine;
        adauga(unde, pecine);
    }
    long contor = 0;

    for (long i = 0; i < n; i++)
        if (!vi[i].vizitat)
            if (vi[i].urmasi.empty())
                contor++, vi[i].vizitat = true;
            else
                depth(i), contor++;

    out << contor  << "\n";
    return 0;
}