#P7666. [JOI 2018 Final] 寒冬暖炉 / Stove

[JOI 2018 Final] 寒冬暖炉 / Stove

Description

There is a stove in JOI's room. Since JOI is used to cold temperatures, when he is alone in his room, he does not need to turn on the stove. However, when there are guests, he needs to turn on the stove.

One day, NN guests will visit JOI. The ii-th guest (1iN1 \leq i \leq N) will arrive at time TiT_i and leave at time Ti+1T_i + 1. At any time, at most one guest visits JOI. JOI can turn the stove on or off at any time.

JOI uses matches to light the stove. JOI has only KK matches, so he can turn on the stove at most KK times. At the beginning of the day, the stove is off. When the stove is on, it consumes fuel. Therefore, JOI controls when to turn the stove on or off, and he wants to minimize the total running time of the stove.

Given the guest visit information and the number of matches JOI has, write a program to compute the minimum possible total running time of the stove.

Input Format

The first line contains two space-separated integers NN and KK. This means that NN guests will visit JOI, and JOI has KK matches.

Each of the next NN lines contains an integer TiT_i on the ii-th line. This means that the ii-th guest will arrive at time TiT_i and leave at time Ti+1T_i + 1.

Output Format

The only line should contain one integer: the minimum total running time of the stove.

3 2
1
3
6
4
3 1
1
2
6
6
3 3
1
3
6
3
10 5
1
2
5
6
8
11
13
15
16
20
12

Hint

Constraints

For 100%100\% of the testdata, 1N1051 \leq N \leq 10^5, 1KN1 \leq K \leq N, 1Ti1091 \leq T_i \leq 10^9 (1iN1 \leq i \leq N), Ti<Ti+1T_i < T_{i+1} (1iN11 \leq i \leq N - 1).

  • Subtask 11 (2020 points): N20N \leq 20.
  • Subtask 22 (3030 points): N5000N \leq 5000.
  • Subtask 33 (5050 points): No additional constraints.

Sample Explanation

For Sample 11: Three guests will visit JOI. If he turns the stove on and off in the following way, the stove is on when guests visit, he turns on the stove twice, and the total running time is (41)+(76)=4(4 - 1) + (7 - 6) = 4.

  • When the first guest arrives, he turns on the stove at time 11.
  • When the second guest leaves, he turns off the stove at time 44.
  • When the third guest arrives, he turns on the stove at time 66.
  • When the third guest leaves, he turns off the stove at time 77.

Since the total running time cannot be smaller than 44, output 44.

For Sample 22: JOI can turn on the stove only once. Therefore, he turns on the stove at time 11 when the first guest arrives, and he turns it off at time 77 when the third guest leaves.
Note that a guest's leaving time may be the same as the next guest's arrival time.

For Sample 33: JOI turns on the stove when each guest arrives, and turns it off when each guest leaves.

Problem Note

This problem comes from T1: Stove of The 17th Japanese Olympiad in Informatics (JOI 2017/2018) Final Round: T1: Stove.
Translated and整理 (zhengli) by @求学的企鹅.

Translated by ChatGPT 5