Simulate K turns on a row of 8-tooth gears where a turning gear rotates its neighbor only if the touching teeth have opposite poles, then count gears whose top tooth is S.
Medium5SimulationImplementationArrayBrute forceInterviewNo attempts yetTime limit2sMemory limit512 MBT gears, each with 8 teeth, sit in a row as in the picture below. Every tooth shows one of two poles, N or S. The gears are numbered from the left, so the leftmost gear is gear 1, the next one is gear 2, and the rightmost one is gear T. The picture below shows the case T = 4.

You turn the gears K times in total. One turn moves a gear by one tooth. A turn goes either clockwise or counter-clockwise, as in the pictures below.


To make a turn you choose the gear to turn and the direction. When a gear turns, the gear beside it may turn with it or may stay still, depending on the poles of the teeth that touch. If gear A turns and the tooth it shares with the gear B beside it has a different pole from B's touching tooth, then B turns in the direction opposite to A. If the two touching teeth have the same pole, B stays still, and a gear that stays still passes nothing on to the gears past it. The touching teeth are tooth 3 of the left gear (the 3 o'clock position) and tooth 7 of the right gear (the 9 o'clock position). Look at the case below.

The green dashed lines mark the parts where two gears touch. If gear 3 turns counter-clockwise here, gear 4 turns clockwise. Gear 2 does not turn because both touching teeth are S, and gear 1 does not turn because gear 2 did not. The result is the shape in the picture below.

From that state, turning gear 1 clockwise turns gear 2 counter-clockwise, and because gear 2 turns, gear 3 turns clockwise at the same time. Gear 4 does not turn because the teeth it shares with gear 3 have the same pole. The result is the state below.

Given the initial state of the T gears and the way they are turned, write a program that finds the final state of the gears.
The first line contains the number of gears T (1 ≤ T ≤ 1,000).
Each of the next T lines gives the state of one gear, from the leftmost gear to the rightmost one. A state is 8 digits with no spaces between them, listed clockwise starting from the 12 o'clock position. An N pole is 0 and an S pole is 1.
The next line contains the number of turns K (1 ≤ K ≤ 1,000). Each of the next K lines describes one turn, in order. A turn is two integers: the number of the gear that is turned, and the direction. A direction of 1 means clockwise, and -1 means counter-clockwise.
Print the number of gears whose 12 o'clock tooth is an S pole after all K turns.