Explanation
The naive approach would be to create a by 2D array that tracks whether node can be reached from node . However, that would clearly take up too much memory ( bytes or MB). We can optimize this using bitsets. Using a 2D array of bitsets, the revised complexity becomes bytes or MB, which is much more efficient.
To do the actual calculation we can just do a DFS and for every node a child can reach, we mark it down for the parent as well.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;const int MAXN = 5e4;vector<int> graph[MAXN + 1];bitset<MAXN + 1> can[MAXN + 1];vector<bool> visited(MAXN + 1);void dfs(int node) {visited[node] = true;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!