Pagini recente » Cod sursa (job #518007) | Cod sursa (job #1853287) | Monitorul de evaluare | Cod sursa (job #195759) | Cod sursa (job #3336530)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream f("dfs.in");
ofstream g("dfs.out");
// void DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
// {
// viz[x - 1] = 1;
// for(int vecin : lista[x - 1])
// if(viz[vecin - 1] == 0)
// DFS(lista, viz, vecin);
// }
void DFS(vector<vector<int>>& lista, vector<int>& viz, int x)
{
viz[x - 1] = 1;
stack<int> stiva;
stiva.push(x);
while(!stiva.empty())
{
int nod = stiva.top();
stiva.pop();
for(int vecin : lista[nod - 1])
{
if(viz[vecin - 1] == 0)
{
viz[vecin - 1] = 1;
stiva.push(vecin);
}
}
}
}
int main()
{
int n, m, x, y;
f >> n >> m;
vector<vector<int>> lista(n);
for(int i = 0; i < m; i++)
{
f >> x >> y;
lista[x - 1].push_back(y);
lista[y - 1].push_back(x);
}
vector<int> viz(n, 0);
int comp_conexe = 0;
for(int i = 0; i < n; i++)
if(viz[i] == 0)
{
comp_conexe++;
DFS(lista, viz, i + 1);
}
g << comp_conexe;
return 0;
}