Table of Contents

ExplanationImplementation

Explanation

The naive approach would be to create a NN by NN 2D array that tracks whether node vv can be reached from node uu. However, that would clearly take up too much memory (2.51092.5 \cdot 10^9 bytes or 25002500 MB). We can optimize this using bitsets. Using a 2D array of bitsets, the revised complexity becomes 2.5109324=3.25108\frac{2.5 \cdot 10^9}{32} \cdot 4 = 3.25 \cdot 10^8 bytes or 312.5312.5 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: O(NM32)\mathcal{O}(\frac{N \cdot M}{32})

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!