Pagini recente » Cod sursa (job #2314139) | Cod sursa (job #1639775) | Cod sursa (job #2442238) | Cod sursa (job #3228825)
#include <fstream>
#include <vector>
using namespace std;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
static constexpr int NMAX = 100005;
int n, m;
vector<int> adj[NMAX];
void read_input() {
ifstream fin("dfs.in");
fin >> n >> m;
for (int i = 0, x, y; i < m; i++) {
fin >> x >> y;
adj[x].push_back(y);
adj[y].push_back(x); // For undirected graph, add both directions
}
fin.close();
}
void dfs(int node, vector<bool> &visited) {
visited[node] = true;
for (auto neighbor : adj[node]) {
if (!visited[neighbor])
dfs(neighbor, visited);
}
}
int get_result() {
int nr = 0;
vector<bool> visited(n + 1, false);
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i, visited);
nr++;
}
}
return nr;
}
void print_output(int nr) {
ofstream fout("dfs.out");
fout << nr;
fout.close();
}
};
int main() {
auto* task = new (nothrow) Task();
if (!task) {
cerr << "new failed: WTF are you doing? Throw your PC!\n";
return -1;
}
task->solve();
delete task;
return 0;
}