APIO '15 P3 - Palembang Bridges

View as PDF

Submit solution

Points: 20 (partial)
Time limit: 1.0s
Memory limit: 256M

Problem types
Allowed languages
Ada, Assembly, Awk, Brain****, C, C#, C++, COBOL, CommonLisp, D, Dart, F#, Forth, Fortran, Go, Groovy, Haskell, Intercal, Java, JS, Kotlin, Lisp, Lua, Nim, ObjC, OCaml, Octave, Pascal, Perl, PHP, Pike, Prolog, Python, Racket, Ruby, Rust, Scala, Scheme, Sed, Swift, TCL, Text, Turing, VB, Zig

The city of Palembang is separated by Musi River into two zones. Let's call them zone A and zone B.

Each zone consists of exactly 1\,000\,000\,001 buildings along the respective side of the river, conveniently numbered 0 through 1\,000\,000\,000. The distance between every pair of adjacent buildings is 1 unit of distance. The width of the river is 1 unit of distance as well. Building i in zone A is located on exactly the opposite side of building i in zone B.

N citizens live and work in the city. Citizen i's house is in zone P_i, building S_i, while his office is in zone Q_i, building T_i. If a citizen must cross the river to go from his house to his office, he must take a boat. This has been uncomfortable, so the government has decided to build at most K bridges over the river, so that the citizens can go to work by driving. Each bridge must be built exactly between two opposite buildings in the two zones. The bridges must be strictly perpendicular to the river. The bridges must not overlap each other.

Let D_i be the minimum distance citizen i has to drive to go from his house to his office, after the government has built at most K bridges. Help the government build the bridges in such a way that the sum D_1 + D_2 + \dots + D_N is minimized.

Input Specification

The first line contains two integers K and N. Each of the next N lines contains four tokens P_i, S_i, Q_i, and T_i.

Output Specification

A single line containing the minimum sum of the distances.

Sample Input 1

1 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7

Sample Output 1


Sample Input 2

2 5
B 0 A 4
B 1 B 3
A 5 B 7
B 2 A 6
B 1 A 7

Sample Output 2



This is the illustration for both sample inputs.

Here is one possible solution for sample input 1. The pink stripe segment denotes a bridge.

And this is a possible solution for sample input 2:


For each subtask,

  • P_i and Q_i will be either a character A or a character B.
  • 0 \le S_i, T_i \le 1\,000\,000\,000
  • More than one house or office (or combination of both) can be located in the same building.
Subtask 1 (8 points)
  • K=1
  • 1 \le N \le 1\,000
Subtask 2 (14 points)
  • K = 1
  • 1 \le N \le 100\,000
Subtask 3 (9 points)
  • K=2
  • 1 \le N \le 100
Subtask 4 (32 points)
  • K=2
  • 1 \le N \le 1\,000
Subtask 5 (37 points)
  • K=2
  • 1 \le N \le 100\,000


  • 1
    KevinWan  commented on Sept. 28, 2017, 12:16 p.m.

    what pink stripe??

    • 1
      Kirito  commented on Sept. 28, 2017, 9:34 p.m.

      Fixed. Sorry about that.