Pagini recente » Cod sursa (job #526538) | Cod sursa (job #2232809) | Cod sursa (job #770976) | Cod sursa (job #1687955) | Cod sursa (job #3249469)
// https://infoarena.ro/problema/dfs
// dfs on a undirected graph
// counting conex components
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
const int NMAX = 1e5 + 5;
vector<int> gp[NMAX];
bool visited[NMAX];
stack<int> st;
int no_of_conex_components = 0;
void DFS(int source)
{
st.push(source);
visited[source] = 1;
while (!st.empty())
{
int node = st.top();
st.pop();
for (auto next : gp[node])
{
if (!visited[next])
{
st.push(next);
visited[next] = no_of_conex_components;
}
}
}
}
int main()
{
int n, m;
fin >> n >> m;
while (m--)
{
int x, y;
fin >> x >> y;
gp[x].push_back(y);
gp[y].push_back(x);
}
for (int i = 1; i <= n; i++)
{
if (!visited[i])
{
no_of_conex_components++;
DFS(i);
}
}
fout << no_of_conex_components;
return 0;
}