Pagini recente » Cod sursa (job #1203574) | Cod sursa (job #673500) | Cod sursa (job #1180360) | Cod sursa (job #2048838) | Cod sursa (job #3254449)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const string file_name = "dfs";
ifstream fin(file_name + ".in");
ofstream fout(file_name + ".out");
struct Vertex {
Vertex(int v) : val(v) {};
bool visited = false;
int parent;
int val;
};
void dfs(vector<vector<Vertex>>& graph, int source)
{
for(Vertex& v: graph[source]) {
if(!v.visited) {
v.visited = true;
dfs(graph, v.val);
}
}
}
int main()
{
int n, m;
fin >> n >> m;
vector<vector<Vertex>> graph(n + 1);
for(int e = 0; e < m; e++)
{
int x, y;
fin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
int conexe = 0;
for(int i = 1; i <= n; i++)
{
for(Vertex& v: graph[i])
{
if(!v.visited)
{
v.visited = true;
dfs(graph, v.val);
++conexe;
}
}
}
fout << conexe;
return 0;
}