A remote sensor-relay network is organized as a binary tree of relay units rooted at a central hub. Every relay can forward its readings to up to two downstream relays: a primary link and a secondary link. During a routine firmware update, exactly one relay's secondary link — which should have been left empty — was mistakenly wired to a relay that already receives a feed from a different, shallower relay elsewhere in the network. This leaves one relay with two independent incoming feeds, and leaves exactly one relay faulty: its only outgoing link is this erroneous duplicate feed.
To restore the network, find that one faulty relay and decommission it — remove it, and every link originating from it, from the network — then report which relays remain.
It is guaranteed that:
n, the number of relay records.n lines: three integers v L R — the i-th relay's signal value v, and the 1-based indices (among these n records) of its primary (L) and secondary (R) downstream relays, or 0 if that link is absent. Relay 1 is always the central hub.m, the number of relays remaining after decommissioning the faulty relay.v are distinct.n relays, rooted at relay 1.Example 1
Input
3 10 2 3 20 0 0 30 0 2
Expected
2 10 20
Explanation
Relay 1 (value 10) is the hub, with a primary link to relay 2 (value 20) and a secondary link to relay 3 (value 30). Relay 3's secondary link wrongly points back at relay 2, which already receives a feed from the hub, so relay 3 is the faulty one. Decommissioning relay 3 leaves only the hub and relay 2, giving m=2 and level order '10 20'.
Example 2
Input
5 100 2 3 50 4 0 90 5 0 40 0 0 80 0 4
Expected
4 100 50 90 40
Explanation
The hub (100) forwards to relay 2 (50) and relay 3 (90), both one level down. Relay 2 forwards to relay 4 (40, two levels down). Relay 5 (80, also two levels down, under relay 3) has an empty primary link but a secondary link that wrongly points at relay 4 — the same depth as relay 5 itself, and relay 4 already has a legitimate feed from relay 2. Decommissioning relay 5 leaves the hub, relay 2, relay 3, and relay 4, giving m=4 and level order '100 50 90 40'.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →