Pagini recente » Cod sursa (job #2952157) | Istoria paginii runda/simulare_de_oni_3/clasament | Cod sursa (job #2081069) | Cod sursa (job #739591) | Cod sursa (job #3126764)
#include <bits/stdc++.h>
using namespace std;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
static constexpr int NMAX = (int)1e5 + 5;
int n, m;
vector<int> adj[NMAX];
void read_input() {
ifstream fin("dfs.in");
fin >> n >> m;
for (int i = 1, x, y; i <= m; i++) {
fin >> x >> y;
adj[x].push_back(y);
}
fin.close();
}
void DFS_RECURSIVE(int node, vector<int> p, int timestamp,
vector<int> start, vector<int> finish) {
start[node] = ++timestamp;
for (int neigh : adj[node]) {
if (p[neigh] == -1) {
p[neigh] = node;
DFS_RECURSIVE(neigh, p, timestamp, start, finish);
}
}
finish[node] = ++timestamp;
}
int get_result() {
vector <int> p (n + 1);
vector<int> start (n + 1);
vector<int> finish (n + 1);
for (int i = 1; i <= n; i++) {
p[i] = -1;
}
int timestamp = 0;
int components = 0;
for (int i = 1; i <= n; i++ ) {
if (p[i] == -1) {
components++;
DFS_RECURSIVE(i, p, timestamp, start, finish);
}
}
return components;
}
void print_output(int components) {
ofstream fout("dfs.out");
fout << components;
fout.close();
}
};
// [ATENTIE] NU modifica functia main!
int main() {
// * se aloca un obiect Task pe heap
// (se presupune ca e prea mare pentru a fi alocat pe stiva)
// * se apeleaza metoda solve()
// (citire, rezolvare, printare)
// * se distruge obiectul si se elibereaza memoria
auto* task = new (nothrow) Task(); // hint: cppreference/nothrow
if (!task) {
cerr << "new failed: WTF are you doing? Throw your PC!\n";
return -1;
}
task->solve();
delete task;
return 0;
}