Chocolate Milk
InterviewTime limit1sMemory limit128 MB
Given a directed tree with N-1 edges where all flow reaches one sink, list every non-source node that lies on every root-to-sink path.
- Level
Medium6 of 10
- Topics
- Graph, DFS, Tree, Implementation
- Solved
- No attempts yet
Problem
Farmer John runs an intricate system for producing and shipping milk. He attaches milking machines to his many cows to harvest milk, which then flows into pipes.
Each pipe connects a milking machine to a joint, where it may be joined by exactly one more pipe (the milk from both pipes then merges). The merged milk flows through further pipes (each starting and ending at a joint) until it reaches the long central pipe leading to the distribution room. From there the milk goes through the reverse process, splitting at various joints until it flows into milk tanks that are picked up and taken to market.
There is at most one way for milk to travel from one joint to any other joint. Moreover, milk flows through every single pipe; that is, no pipe is unneeded.
If we regard each milking machine, joint, and milk tank as a node, there are nodes in total (), connected by pipes. Each pipe is given as an ordered pair of nodes and (, , ), indicating that milk flows from node to node . A node with no incoming pipe is a milking machine, and a node with no outgoing pipe is a tank.
With chocolate milk demand soaring, Farmer John wants to install a chocolate inserter at one joint to make delicious chocolate milk. Because he has only one inserter, he wants to place it at a joint through which all of the milk passes. He knows such a joint exists.
Find every joint at which the chocolate inserter can be installed. (It cannot be installed at a milking machine.)
For example, consider a setup like the following.
1 ----+
|
v
2 --> 4 --> 6 ------------------> 7 --> 8
^ |
| |
3 --> 5 ----+ + --> 9
All milk passes through joints 6 and 7, so the chocolate inserter can be installed at either of them.
Input
- Line 1: a single integer .
- Lines 2 to : each line contains two space-separated integers and describing the connectivity of one pipe.
Output
Print the numbers of all joints at which the chocolate inserter can be installed, one per line, in ascending order.