Ghostbusters
Time limit2sMemory limit512 MB
Given independent button press probabilities, find the most likely set of pressed buttons that produces the observed row-to-column connectivity signals.
- Level
Hard8 of 10
- Topics
- Graph, Dynamic programming, Probability, Math
- Solved
- No attempts yet
Problem
A keyboard is a grid of rows and columns of buttons. Every row has one cable and every column has one cable. Pressing the button in row and column connects the cable of row with the cable of column .
The firmware detects presses by sampling. It sends an electric signal into the cable of row 0. The signal spreads to every column cable joined to that row by a pressed button, then to every row cable joined to those columns by a pressed button, and so on. Every cable connected to the starting row through pressed buttons, directly or indirectly, receives the signal. The firmware records which columns received it, and repeats the whole process for every row.
A single press is easy to locate, because exactly one pair (row, column) makes contact. A keyboard also allows several buttons at once, and some combinations cannot be told apart. This effect is called ghosting. On a keyboard, for example, every combination of three or four presses connects all four cables, so the recorded signals are identical.

Four examples of connected cables. Bold lines of the same colour mark cables joined by pressed buttons, drawn as red dots. The two sets on the right cannot be told apart, because they connect the same rows and the same columns.
Each button has its own probability of being pressed, and the buttons are pressed independently of each other. The probability of a set of pressed buttons is the product of over the buttons in , times the product of over the buttons outside . Given the recorded signals, find the set of pressed buttons that could produce them and has the largest probability.
Input
The first line has two integers and , the number of rows and the number of columns. ()
Each of the next lines has real numbers. The -th number on the -th line is the probability that the button in row and column is pressed. () Rows and columns are numbered from 0, so and .
Each of the next lines starts with an integer () followed by integers. Those integers are the columns that received the signal sent into row .
The recorded signals always come from some real set of pressed buttons.
Output
Print the set of pressed buttons with the largest probability. For each pressed button print one line with two integers and , separated by a space: the row and the column of the button. Print the lines in increasing order of , and in increasing order of among equal .
If several sets reach the largest probability, print the lexicographically smallest one. Compare the sequences of (row, column) pairs sorted in the order above, and take the set whose first differing pair is smaller. If no button is pressed, print nothing.