Flip Pipes to Flow Outward From a Source Station
Trees & GraphsAuto-graded · 18 test casesLast 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 ofn-1pairs[a, b], each describing a pipe that currently runs fromatob.source: the station that flow must move away from.
Output
- A single integer: the minimum number of flips.
Constraints
1 <= n <= 2 * 10^5len(pipes) == n - 1- Ignoring direction,
pipesforms a tree over stations0..n-1. 0 <= source < n- When
n = 1, there are no pipes and the answer is0. - Deep trees are possible (for example a path of
2 * 10^5stations), 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
After choosing source as the root, every pipe has one forced direction: from the endpoint closer to the root (the parent) to the farther one (the child). A pipe that already runs parent to child is fine. A pipe that runs child to parent must be flipped. Flipping a correct pipe would only make it wrong. So the answer is simply the number of pipes that currently point toward the root.
To count them during a traversal, put every pipe in both endpoints' adjacency lists with a cost tag:
- For a pipe
a -> b, add(b, 0)toadj[a]: walking fromatobfollows the pipe, so no flip is needed. - Add
(a, 1)toadj[b]: walking frombtoagoes against the pipe, so if the traversal reachesathis way, the pipe must be flipped.
Run an iterative DFS (or BFS) from source. Each time a new station v is discovered from u, u is v's parent, and the pipe's cost tag says whether it must be flipped. Add that cost to the total.
Why it is correct
- The graph is a tree, so each non-root station is discovered exactly once, through its unique parent pipe. Every pipe is therefore counted exactly once.
- The cost tag is 1 exactly when the pipe currently points from child to parent, i.e. when it is wrongly oriented.
- Each pipe's required direction is fixed by the rooting and pipes are independent, so every wrong pipe must be flipped and no other needs to be. The count is both necessary and sufficient, hence minimal.
Edge cases
n = 1: no pipes, answer0.- All pipes already point away from the source: answer
0. - All pipes point toward the source: answer
n - 1. - Very deep trees: the explicit stack avoids recursion limits.
Complexity
- Time:
O(n), since each of the2(n-1)adjacency entries is scanned once. - Space:
O(n)for the adjacency lists, visited array and stack.
Reference solution
from typing import List
def min_flips_from_source(n: int, pipes: List[List[int]], source: int) -> int:
# adj[x] holds (neighbor, cost): cost is 1 when walking x -> neighbor
# goes against the pipe's current direction.
adj = [[] for _ in range(n)]
for a, b in pipes:
adj[a].append((b, 0))
adj[b].append((a, 1))
flips = 0
seen = [False] * n
seen[source] = True
stack = [source]
while stack:
u = stack.pop()
for v, cost in adj[u]:
if seen[v]:
continue
seen[v] = True
flips += cost
stack.append(v)
return flips