#P3615. [JOISC 2016] 如厕计划 / Toilets

[JOISC 2016] 如厕计划 / Toilets

Description

After the contest, the contestants with full bladders file out. The restroom planning at Fanhua High School is terrible: there are only two stalls, so a long line forms in front of the restroom.

There are two restrooms: one is female-only, and the other is unisex. There are 2N2N contestants in total waiting in line, and the numbers of males and females may differ. If the head of the queue is female, she may enter as soon as any restroom is free; if both restrooms are free, she prefers the female-only restroom. If the head of the queue is male, he can only use the unisex restroom when it is free; if only the female-only restroom is free, then the earliest female in the queue may immediately enter without waiting. Assume each person occupies a restroom for 11 minute, and ignore switching time.

However, after NN minutes dinner starts, and everyone must have finished using the restroom, which seems impossible. The organizers may reorder the queue, but some people will be unhappy because they are placed later than before. A person’s dissatisfaction is the number of positions they move backward compared to the original queue (it is otherwise unrelated to their actual time of using the restroom).

The organizers want your help to design a plan that minimizes the maximum dissatisfaction among all students. You only need to report the dissatisfaction of the most dissatisfied student.

Input Format

Because there are many people, we describe the queue using several string blocks.

  • The first line contains an integer NN.
  • The second line contains an integer MM.
  • The next MM lines each contain a string SiS_i and an integer KiK_i, separated by a space. The string contains only M (male) and F (female). The final string equals S1S_1 repeated K1K_1 times + S2S_2 repeated K2K_2 times + ... + SMS_M repeated KMK_M times.

Output Format

Output a single integer, the answer. If it is impossible to finish within NN minutes no matter how you reorder, output -1.

5
3
FFF 1
M 5
FF 1
2

Hint

The original queue is FFFMMMMMFF,

the improved queue is FMMFFMMMFF,

so the restrooms are used as follows:

分钟 1   2   3   4   5
共用 2   3   6   7   8
女用 1   4   5   9   10

Two females move backward by 22 positions, so the dissatisfaction is 22.

For 20%20\% of the testdata, N10N \le 10, M=1M = 1, K1=1K_1 = 1.

For 40%40\% of the testdata, N100000N \le 100000, M=1M = 1, K1=1K_1 = 1.

For 100%100\% of the testdata, 1N,Ki10181 \le N, K_i \le 10^{18}, 1M1000001 \le M \le 100000, Si200000\sum |S_i| \le 200000.

Translated by ChatGPT 5