progress

~/problems / Tree techniques / Euler tour of a tree

Upstream or downstream?

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A river system is a tree of stations 0 .. n-1 joined by n - 1 undirected channels, with the mouth at root. Station a is downstream of b when a is a proper ancestor of b (it lies on b's path to the mouth).

For each query (a, b) report "same" if a == b, "downstream" if a is a proper ancestor of b, "upstream" if it's a proper descendant, and "separate" otherwise.

Implement relations(n, channels, root, queries) -> list[str].

#        0 (mouth)
#       / \
#      1   2
#     / \
#    3   4
channels = [(0, 1), (0, 2), (1, 3), (1, 4)]
relations(5, channels, 0, [(1, 4), (4, 0), (3, 2), (2, 2)])
# ["downstream", "upstream", "separate", "same"]

Up to 10^5 stations and queries.

⭐ Bonus: walking up the tree per query still passes; speed tests on rivers 10^5 stations long earn a star at O(1) per query. Recursion overflows on those, so use an iterative DFS.

Show hint

one DFS gives entry/exit times; a is an ancestor of b (or equal) exactly when tin[a] <= tin[b] and tout[b] <= tout[a].

Topic: Euler tour of a tree. Flatten subtrees into contiguous ranges with tin/tout.

0:00
Ctrl ' run · Ctrl ↵ submit
esc