Pagini recente » Cod sursa (job #2490347) | Cod sursa (job #1667286) | Cod sursa (job #3268858) | Cod sursa (job #2835083) | Cod sursa (job #3220478)
#include <iostream>
#include <stack>
#include <fstream>
#include <vector>
std::ifstream fin("dfs.in");
std::ofstream fout("dfs.out");
class Node
{
int value;
Node* next;
public:
Node(int x = 0, Node* adr = nullptr) : value(x), next(adr) {}
void set_value(int value) { this->value = value; }
void set_next(Node* next) { this->next = next; }
Node* get_next() { return next; }
int get_value() { return value; }
Node& operator= (const Node& altul)
{
this->next = altul.next;
this->value = altul.value;
return *this;
}
};
void create_connection(std::vector <Node>& v, int head, int tail)
{
Node* A = new Node();
A->set_value(tail);
A->set_next(v[head].get_next());
v[head].set_next(A);
}
void DFS(std::vector <Node>& lista, int (&descoperit)[], int x, int &comp_conexe)
{
descoperit[x] = comp_conexe;
Node* A = &(lista[x]);
while (A->get_next() != nullptr)
{
A->set_value(A->get_next()->get_value());
A->set_next(A->get_next()->get_next());
int val = A->get_value();
if (descoperit[val] == 0)
DFS(lista, descoperit, val, comp_conexe);
}
}
int main()
{
std::vector < Node > lista ;
int n, m, x , y;
fin >> n >> m;
lista.resize(n+1);
for (int i = 0; i <= n; i++)
lista[i].set_value(i);
for (int count = 1; count <= m; ++count)
{
fin >> x >> y;
create_connection(lista, x, y);
create_connection(lista, y, x);
}
int descoperit[n+1] = { 0 };
int nod, comp_conexe = 0;
bool gata = false;
while(gata == false)
{
gata = true;
for (int i = 1; i <= n && gata; ++i)
if (descoperit[i] == 0)
{ gata = false; nod = i; }
if (!gata)
{
comp_conexe++;
DFS(lista, descoperit, nod, comp_conexe);
}
}
fout << comp_conexe;
}