Cod sursa(job #2609938)

Utilizator mzzmaraMara-Ioana Nicolae mzzmara Data 3 mai 2020 20:12:03
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h> 

using namespace std;

const int kNmax = 100005;

class Task {
 public:
	void solve() {
		read_input();
		print_output(get_result());
	}

 private:
	int n;
	int m;
	vector<int> adj[kNmax];
	vector<int> adjt[kNmax];

	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);
			adjt[y].push_back(x);
		}
		fin.close();
	}

	int get_result() {
        int solution = 0;
        std::vector<bool> visited(n + 1, false);
        for (int i = 1; i <= n ; i++) {
            if (!visited[i]) {
                dfsHelper(i, visited);
                solution++;
            }
        }
        return solution;
	}


	void dfsHelper(int node, std::vector<bool> &visited) { 
        visited[node] = true;
        for (auto& adj : adj[node]) {
            if (!visited[adj]) {
                dfsHelper(adj, visited);
            }
        }
    }

	void print_output(int result) {
		ofstream fout("dfs.out");
		fout << result << '\n';
		fout.close();
	}
};

int main() {
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}