Stargates
Time limit1sMemory limit128 MB
Implement a union-find structure over up to 6,000,000 nodes supporting batched connect and query commands defined by arithmetic sequences of pairs.
- Level
Medium6 of 10
- Topics
- Union-find, Implementation, Simulation
- Solved
- No attempts yet
Problem
Long ago, in a distant galaxy, an advanced civilization discovered instant travel between solar systems and began building pairs of stargates that link far-apart planets. Their network grew so complex that they need help tracking which worlds are connected.
Write a program that maintains connectivity information about the systems. Two planets and are connected if there is a direct stargate between them, or if there is a sequence of planets with and such that and are directly connected for every . All connections are bidirectional, and there may be several paths between two planets.
Input
The input consists of one or more data sets and contains no blank lines. Each command is on its own line and starts with a single letter — 'D', 'C', or 'Q' (upper or lower case) — followed by to integers:
- 'D' (define) takes one integer (): it starts a new data set with planets numbered to and no connections.
- 'C' (connect) adds stargate connections between one or more pairs of planets.
- 'Q' (query) asks whether one or more pairs of planets are connected.
The 'C' and 'Q' commands (written 'X' below) share the same argument syntax:
X src dst— one pair .X src dst nnn— the pairs . For example,X 1 100 3refers to .X src dst nnn step— the pairs for . For example,X 1 100 3 5refers to .X src dst nnn dststep srcstep— the pairs for . For example,X 1 100 3 5 15refers to .
For a 'C' command every listed pair is connected; for a 'Q' command every listed pair is tested. All referenced planet numbers lie between and the current .
Output
Print one line for every 'Q' (query) command, in order. Each line contains two integers separated by the three-character sequence ' - ' (a space, a hyphen-minus, and a space): first the number of pairs in that query that are connected, then the number of pairs that are not connected. Do not print any trailing spaces.