Passing Cars
InterviewTime limit1sMemory limit128 MB
Count pairs of cars moving toward each other where an eastbound car stands west of a westbound car.
- Level
Easy3 of 10
- Topics
- Prefix sum, Array
- Solved
- No attempts yet
Problem
Przemek watches the cars on a road. The road is two-way and connects the eastern side of the city with the western side. Standing on a hill, Przemek can see the exact position of every car.
He wants to know how many pairs of cars will pass each other. Two cars pass each other when they drive in opposite directions and, of the two, the one that is further west is heading east while the one that is further east is heading west, so they move toward each other and cross. Assume the cars never turn around, never overtake, and always drive straight ahead.
Given the driving directions of the cars listed from west to east, count how many pairs of cars will pass each other.
Input
The first line contains an integer (), the number of cars.
The second line contains integers (each ). The cars are given in order from the westmost to the eastmost (car is further west than car ), and is the driving direction of car : means the car drives east, and means the car drives west.
Output
Print a single integer: the number of pairs of cars that will pass each other.
Hint
A pair with passes if and only if car drives east (0) and car drives west (1). So the answer equals the number of ordered pairs in which a 0 appears before a 1. Scan from the left, keep a running count of the east-bound (0) cars seen so far, and add that count to the answer every time you meet a west-bound (1) car.