Switches
Time limit2sMemory limit512 MB
Given initial on-lamps and N switches that each toggle a set of lamps, find how many flips are made cycling 1..N until all lamps are off, or -1 if never.
- Level
Medium7 of 10
- Topics
- Simulation, Math, Implementation, Bit manipulation
- Solved
- No attempts yet
Problem
On the control panel of a large amphitheater there are N switches, numbered 1 to N, that control the M lamps in the venue, numbered 1 to M. The number of switches and lamps is not necessarily the same, because each switch is associated with a set of lamps rather than a single lamp. When a switch is flipped, the state of each lamp associated with it is inverted. That is, lamps that are off turn on and lamps that are on turn off.
Some lamps are on initially, and the caretaker of the amphitheater needs to turn all the lamps off. He started by flipping switches at random, but since he could not turn all the lamps off at the same time, he decided to follow a fixed strategy. He will flip the switches in the order 1, 2, 3, ..., N, 1, 2, 3, ..., that is, every time after flipping switch number N he starts the sequence again from switch 1. He intends to keep flipping switches, following this strategy, until all the lamps are off at the same time, at which point he stops flipping. Will this strategy work?
In this problem, given the lamps that are on initially and the sets of lamps associated with each switch, your program must compute the number of times the caretaker will flip the switches. If the caretaker's strategy never turns all the lamps off at the same time, your program must print −1.
Input
The first line contains two integers N and M (1 ≤ N, M ≤ 1000) representing the number of switches and the number of lamps, respectively.
The second line contains an integer L (1 ≤ L ≤ M) followed by L distinct integers Xi (1 ≤ Xi ≤ M), representing the lamps that are on initially.
Each of the following N lines contains an integer Ki (1 ≤ Ki ≤ M) followed by Ki distinct integers Yi (1 ≤ Yi ≤ M), representing the lamps associated with switch i (1 ≤ i ≤ N).
Output
Your program must produce a single line containing an integer representing the number of times the caretaker will flip the switches, following the strategy described, until all the lamps are off at the same time. If this never happens, print −1.