Palembang Bridges
Time limit2sMemory limit256 MB
Choose positions for up to two bridges so the total driving distance of all citizens is minimized.
- Level
Medium7 of 10
- Topics
- Sorting, Greedy, Prefix sum
- Solved
- No attempts yet
Problem
The Musi River runs through the city of Palembang and splits it into two districts. Call them district A and district B.
Each district has exactly 1,000,000,001 buildings along the bank, numbered 0 to 1,000,000,000 in order. Two neighbouring buildings are 1 unit apart, and the river is 1 unit wide. Building of district A sits directly across the river from building of district B.
citizens live and work in the city. Citizen lives in building of district and works in building of district . A citizen whose home and office are in different districts has had to cross the river by boat. Boats are inconvenient, so the city wants to build at most bridges so that every citizen can commute by car alone. A bridge must be perpendicular to the river, so it joins two buildings with the same number, and two different bridges use different numbers.
After the bridges are built, let be the shortest distance citizen can drive from home to the office. Place the bridges so that is as small as possible, and report that minimum.
Input
The first line contains and . Each of the next lines contains , , , , separated by spaces.
- and are the single character 'A' or 'B'.
- Two different citizens may have their homes or offices in the same building, and one citizen's home may be the same building as another citizen's office.
Output
Print the minimum total commuting distance on one line.
Hint
This picture shows both example inputs.

One optimal placement for the first example. The pink part is the bridge.

One optimal placement for the second example.
