Switching Lights
InterviewTime limit1sMemory limit128 MB
Maintain a binary array of N lights under M range-toggle and range-count operations, and print each query result.
- Level
Medium5 of 10
- Topics
- Segment tree, Array, Prefix sum
- Solved
- No attempts yet
Problem
Farmer John keeps his cows sharp by letting them play with intellectual toys. One of the larger toys is the set of lights in the barn. Each of the N () cow stalls, conveniently numbered , has a colorful light above it.
At the beginning of the evening, all lights are off. The cows control the lights with a set of N pushbutton switches. Pushing switch changes the state of light from off to on, or from on to off (a toggle).
The cows read and execute a list of M () operations. Each operation is distinguished by a leading integer that is either or .
An operation of type is followed by two integers and () indicating a starting and an ending switch. It is executed by pushing each switch from through inclusive exactly once.
An operation of type is followed by two integers and () specifying an inclusive range; the cows count how many lights are on within that range.
Process the entire list and produce the correct count for every type- operation.
Input
- Line 1: Two space-separated integers, and .
- Lines : Each line describes one operation as three space-separated integers: the operation type, , and .
Output
- For each type- (counting) operation, print the count as a single integer on its own line.
Hint
An example run with four lights and five commands:
Lights
1 2 3 4
Init: O O O O O = off, * = on
0 1 2 -> * * O O toggle lights 1 and 2
0 2 4 -> * O * * toggle lights 2, 3, and 4
1 2 3 -> 1 count lit lights in range 2..3
0 2 4 -> * * O O toggle lights 2, 3, and 4
1 1 4 -> 2 count lit lights in range 1..4