Pagini recente » Cod sursa (job #2279141) | Cod sursa (job #2552284) | Cod sursa (job #1735833) | Cod sursa (job #1879852) | Cod sursa (job #3165879)
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <fstream>
#include <map>
using namespace std;
ifstream fin("dfs.in");
ofstream fout("dfs.out");
vector<int> graf[100001];
int n, m, s;
map<int, bool> visited;
int dist[100001];
queue<pair<int, int>> q;
void bfs()
{
q.push({s, 0});
visited[s] = true;
int cNode, pas;
while (!q.empty())
{
cNode = q.front().first;
pas = q.front().second + 1;
dist[cNode] = pas - 1;
for (int i = 0; i < graf[cNode].size(); i++)
{
if (!visited.count(graf[cNode][i]))
{
visited[graf[cNode][i]] = true;
q.push({graf[cNode][i], pas});
}
}
q.pop();
}
}
stack<int> st;
void dfs(int nod)
{
st.push(nod);
visited[nod] = true;
int cNode;
while (!st.empty())
{
cNode = st.top();
st.pop();
for (int i = 0; i < graf[cNode].size(); i++)
{
if (!visited.count(graf[cNode][i]))
{
visited[graf[cNode][i]] = true;
st.push(graf[cNode][i]);
}
}
}
}
int main()
{
fin >> n >> m; // >> s;
int x, y;
for (int i = 0; i < m; i++)
{
fin >> x >> y;
graf[x].push_back(y);
graf[y].push_back(x);
}
/*
for (int i = 1; i <= n; i++)
{
dist[i] = -1;
}
bfs();
for (int i = 1; i <= n; i++)
{
fout << dist[i] << ' ';
}
*/
int cnt = 0;
for (int i = 1; i <= n; i++)
{
if (!visited.count(i))
{
cnt++;
dfs(i);
}
}
fout << cnt;
return 0;
}