APIO '15 P3 - Palembang Bridges

View as PDF

Submit solution


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

Problem types

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 1000000001 buildings along the respective side of the river, conveniently numbered 0 through 1000000000. 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 Pi, building Si, while his office is in zone Qi, building Ti. 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 Di 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 D1+D2++DN is minimized.

Input Specification

The first line contains two integers K and N. Each of the next N lines contains four tokens Pi, Si, Qi, and Ti.

Output Specification

A single line containing the minimum sum of the distances.

Sample Input 1

Copy
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

Copy
24

Sample Input 2

Copy
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

Copy
22

Explanation

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:

Subtasks

For each subtask,

  • Pi and Qi will be either a character A or a character B.
  • 0Si,Ti1000000000
  • More than one house or office (or combination of both) can be located in the same building.
Subtask 1 (8 points)
  • K=1
  • 1N1000
Subtask 2 (14 points)
  • K=1
  • 1N100000
Subtask 3 (9 points)
  • K=2
  • 1N100
Subtask 4 (32 points)
  • K=2
  • 1N1000
Subtask 5 (37 points)
  • K=2
  • 1N100000

Comments


  • 2
    404  commented on June 5, 2022, 9:04 p.m. edited

    K only goes up to 2... i wasted so much time thinking it went up to 100000