Satoshi, who has strong obsessions with Chinese domestic RPG, will never miss the marvelous game, Gu Jian Qi Tan II, a.k.a., the Legend of Ancient Sword II, because of its gorgeous graphics, picturesque characters and lively design.
Recently, Satoshi has some troubles in the new battle mode of the game, and seeks you for help to solve the problems.
Specifically, in the new instant-action mode, Satoshi can control N roles, and his goal is to kill all M tiny monsters to declare victory. The tiny monsters are too fragile to survive from any skills of any roles. In every second, Satoshi can choose to operate one single role once, or do nothing. However, to make his series of operations magnificent, he would not use same role in any two consecutive seconds, i.e., the role used in i-th second cannot be used in the (i+1)-th second anymore.
For each role, we know the number of skills he/she owns, as well as the LPT (loop time) of each skill, which indicates that the skill could be performed in every LPT seconds starting from the beginning (e.g., if the LPT of a skill is 3, Satoshi could cast the skill at 3s, 6s, 9s, ..., so on and so forth). Moreover, the information of whether a skill can reach (touch) a certain monster is also provided (i.e., whether a monster is within the attacking range of a specific skill). Your task is to help Satoshi use the minimum amount time to win the game; ties are broken by preferring fewer number of operations, which is counted by the number of seconds in which Satoshi chooses to operate a role instead of doing nothing.
Note that Satoshi could choose a certain role, and of course no roles, in a specific second. And when he operates a role in a specific second, he can cast all the available skills (subject to the the LPT constraints) if he wants. Time begins with the 1st second.