KatInterview

Flip Pipes to Flow Outward From a Source Station

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphstreegraph-traversaldfs

Last updated

Count the directed edges of a tree that point toward a chosen root, which is the minimum number of flips needed to orient every edge away from it.

A network has n stations numbered 0 to n-1, joined by n-1 one-way pipes. Each pipe is a pair (a, b), meaning that flow currently goes from station a to station b. If you disregard the direction of the pipes, the network is a tree: it is connected and has no cycles.

One station, source, is the origin of the flow. Flow must travel outward from it: once the tree is hung from source, every pipe should carry flow from the station nearer to source to the station farther from it.

Flipping a pipe swaps its direction (a -> b becomes b -> a) and costs 1. Pipes may be flipped in any combination.

Compute the smallest total number of flips needed so that every pipe carries flow away from source.

Input

  • n: the number of stations.
  • pipes: a list of n-1 pairs [a, b], each describing a pipe that currently runs from a to b.
  • source: the station that flow must move away from.

Output

  • A single integer: the minimum number of flips.

Constraints

  • 1 <= n <= 2 * 10^5
  • len(pipes) == n - 1
  • Ignoring direction, pipes forms a tree over stations 0..n-1.
  • 0 <= source < n
  • When n = 1, there are no pipes and the answer is 0.
  • Deep trees are possible (for example a path of 2 * 10^5 stations), so be careful about recursion depth.

Examples

Example 1

Input: min_flips_from_source(5, [[1, 0], [0, 2], [3, 2], [3, 4]], 0)

Output: 2

Hints

Hint 1

Once you pick the source as the root, every pipe has exactly one required direction: from the parent to the child. So no real optimization is needed.

Hint 2

Each pipe is either already correct or must be flipped, and the pipes are independent. The answer is the number of pipes that currently run from child to parent.

Hint 3

Store each pipe in both endpoints' adjacency lists, with a cost tag of 0 when you traverse it along its direction and 1 when you traverse it against it. Then traverse from the source, using an explicit stack or a queue, and sum the cost of the pipe used to discover each new station.