You are given n riders and a list of events. Each event is [timestamp, type, a, b], where type is one of:
- 'RIDE': riders a and b become permanently connected in the ride graph.
- 'BLOCK': pair (a, b) becomes blocked.
- 'UNBLOCK': remove the block on pair (a, b) if it exists.
At time t, the ride graph contains all RIDE edges with timestamp <= t. A pair of riders is required to be connected only if that pair is not currently blocked. The network is considered fully connected under blocking constraints if every unblocked pair of riders lies in the same ride-connected component. Equivalently, any pair of riders that is in different ride components must currently be blocked.
Return the earliest timestamp when this condition is true after applying all events at that timestamp. If it never becomes true, return -1. If n is 1, return 0.
Notes:
- Events may be unsorted.
- RIDE edges never disappear.
- Repeated BLOCK on an already blocked pair or UNBLOCK on a non-blocked pair has no extra effect.
- For the same unordered pair and the same timestamp, there will not be both a BLOCK and an UNBLOCK event.
Examples
Input: (3, [[1, 'RIDE', 0, 1], [2, 'BLOCK', 0, 2], [2, 'BLOCK', 1, 2]])
Expected Output: 2
Explanation: At time 2, riders 0 and 1 are connected, and both cross-component pairs involving rider 2 are blocked. Therefore every unblocked pair is connected.
Input: (4, [[1, 'BLOCK', 0, 2], [1, 'BLOCK', 0, 3], [1, 'BLOCK', 1, 2], [1, 'BLOCK', 1, 3], [2, 'RIDE', 0, 1], [3, 'RIDE', 2, 3]])
Expected Output: 3
Explanation: At time 3, the two ride-components are {0,1} and {2,3}. All four cross pairs between those components are blocked, so the condition holds.
Input: (3, [[1, 'BLOCK', 0, 2], [2, 'RIDE', 0, 1], [3, 'UNBLOCK', 0, 2], [4, 'RIDE', 1, 2]])
Expected Output: 4
Explanation: The unblock at time 3 breaks the condition. It becomes true again only when the whole ride graph becomes connected at time 4.
Input: (4, [[1, 'RIDE', 0, 1], [2, 'BLOCK', 0, 2]])
Expected Output: -1
Explanation: There are still many unblocked pairs across different ride-components, so the condition is never satisfied.
Input: (1, [])
Expected Output: 0
Explanation: A single rider satisfies the condition immediately.