Splitstream
InterviewTime limit3sMemory limit1024 MB
Given a network of split and merge nodes fed by 1 to m, answer queries for the kth number on any output node.
- Level
Medium5 of 10
- Topics
- Recursion, Simulation, Implementation
- Solved
- No attempts yet
Problem
A splitstream system is an acyclic network of nodes that processes finite sequences of numbers. There are two types of nodes (see Figure J.1).
A split node takes a sequence as input and distributes its numbers alternately to two outputs. The first number goes to output 1, the second to output 2, the third to output 1, and so on.
A merge node takes two sequences as input and merges them alternately into one output. The output contains the first number from input 1, then the first number from input 2, then the second number from input 1, then the second from input 2, and so on. If one input is shorter, the remaining numbers from the longer sequence are passed through unmerged after the shorter sequence runs out.

Figure J.1: How split and merge nodes work.
The overall network has one input, the sequence of positive integers 1, 2, 3, ..., m. Any output of any node can be queried. A query asks for the kth number in the sequence of a given output. Your task is to answer these queries efficiently.
Input
The first line contains three integers m, n, and q. m () is the length of the input sequence, n () is the number of nodes, and q () is the number of queries.
The next n lines describe the nodes, one per line. A split node has the format S x y z, where x is its input, y is its first output, and z is its second output. A merge node has the format M x y z, where x is its first input, y is its second input, and z is its output. The identifiers x, y, and z are distinct positive integers. The overall input is identified by 1, and the remaining input and output identifiers form a consecutive sequence starting at 2. Every input identifier except 1 appears as exactly one output. Every output identifier appears as the input of at most one node.
Each of the next q lines contains a query with two integers x and k. x () is a valid output identifier, and k () is the index of the desired number in that sequence. Indexing starts at 1.
Output
For each query x and k, print on its own line the kth number in the sequence for output x. If that sequence has no kth element, print none.