#BS0000460. Khớp răng đều (Smooth Occlusion)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Khớp răng đều (Smooth Occlusion)
Smooth Occlusion
Source: AtCoder
Version: Phuoc Hung OJ Extended
Problem Statement
Takahashi has upper and lower teeth, numbered from left to right. Their initial lengths at position are and , respectively.
Let denote the final lengths. A good fit requires both of these conditions:
- There is an integer such that for every .
- Adjacent upper teeth satisfy for every .
For one yen, he may shorten a single tooth of positive length by one unit. He may repeat this operation freely; no other change is allowed. Zero final length is permitted.
Determine the minimum total cost of achieving a good fit.
Input
The first line contains integers .
Each of the next lines contains for the corresponding position.
Output
Print the minimum cost as an integer.
Subtasks
- Subtask 1 (20 points): ; ; ; .
- Subtask 2 (30 points): ; ; ; .
- Subtask 3 (50 points): ; ; ; .
Examples
Input 1
4 3
3 1
4 1
5 9
2 6
Output 1
15
Explanation 1
Upper lengths 3,3,3,2 and lower lengths 1,1,1,2 give height 4 and satisfy the adjacent bound. The initial sum is 31, the final sum is 16, and the first pair bounds H by 4.

Input 2
4 1000000000
3 3
3 3
3 3
3 3
Output 2
0
Explanation 2
All pairs already sum to 6 and the upper lengths agree.
Input 3
4 1
1000000000 1000000000
1000000000 1000000000
1000000000 1000000000
1 1
Output 3
5999999994
Explanation 3
The last pair bounds H by 2. Setting all lengths to 1 achieves it; the initial and final sums are 6000000002 and 8.
Input 4
15 128
748 169
586 329
972 529
432 519
408 587
138 249
656 114
632 299
984 755
404 772
155 506
832 854
353 465
387 374
567 385
Output 4
9460
Explanation 4
Height 380 is feasible with upper lengths 380, 380, 380, 380, 266, 138, 266, 380, 380, 283, 155, 283, 353, 380, 380. Lower lengths are H minus the corresponding upper length. The total reduction is 9460. The adjacent bound from position 6 limits upper length at position 7 to 266, so H cannot exceed 380.