This page is still under construction.

Parts of this page are still being built. What you see may change.

Chocolate Milk

Interview

Time limit1sMemory limit128 MB

Summary
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 NN nodes in total (2≤N≤100,0002 \le N \le 100{,}000), connected by N−1N-1 pipes. Each pipe is given as an ordered pair of nodes AiA_i and BiB_i (1≤Ai≤N1 \le A_i \le N, 1≤Bi≤N1 \le B_i \le N, Ai<BiA_i < B_i), indicating that milk flows from node AiA_i to node BiB_i. 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 NN.
  • Lines 2 to NN: each line contains two space-separated integers AiA_i and BiB_i 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.

Examples1

  1. Example 1

    Input
    9
    1 4
    3 5
    2 4
    5 6
    6 7
    7 8
    4 6
    7 9
    
    Expected output
    6
    7