Palembang Bridges

No attempts yetTime limit2sMemory limit256 MB

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 ii of district A sits directly across the river from building ii of district B.

NN citizens live and work in the city. Citizen ii lives in building SiS_i of district PiP_i and works in building TiT_i of district QiQ_i. 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 KK 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 DiD_i be the shortest distance citizen ii can drive from home to the office. Place the bridges so that D1+D2++DND_1 + D_2 + \cdots + D_N is as small as possible, and report that minimum.

Input

The first line contains KK and NN. Each of the next NN lines contains PiP_i, SiS_i, QiQ_i, TiT_i, separated by spaces.

  • PiP_i and QiQ_i are the single character 'A' or 'B'.
  • 0Si,Ti1090 \le S_i, T_i \le 10^9
  • 1K21 \le K \le 2
  • 1N1000001 \le N \le 100\,000
  • 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.