Under construction

Still being built. Things may change

Efficient Slabstones Rearrangement

Time limit2sMemory limit1024 MB

Summary
Shift the n slabstones with the least total movement so a new slabstone of length x fits while every pair keeps at least d empty regions between them.
Level

Medium7 of 10

Topics
Dynamic programming, Greedy, Implementation
Solved
No attempts yet

Problem

Barbara has a garden. The garden is long and narrow, divided into mm equal-sized regions arranged in a row. Her friend, Babara, gave her nn slabstones as a birthday present. Barbara placed these slabstones in her garden so she can enjoy stepping from one slabstone to another every day. The ii-th slabstone fully occupies regions lil_i to rir_i. The slabstones do not overlap, and any two slabstones have at least dd empty regions between them.

Barbara recently bought another slabstone that occupies xx consecutive regions. She will shift the original slabstones within the garden, then place the new slabstone somewhere in the garden. After shifting the original slabstones and placing the new slabstone, the slabstones cannot overlap, and any two slabstones must have at least dd empty regions between them. The slabstones must also stay non-overlapping during the rearrangement.

Shifting a single slabstone to an adjacent region takes one minute. For example, the rearrangement above takes 4 minutes. Barbara wants to know the minimum possible total time required to rearrange the slabstones, so she can save time for other purposes.

Input

The first line contains four integers nn, mm, dd and xx. The ii-th of the following nn lines contains two integers lil_i and rir_i.

Output

Print the minimum possible total time (in minutes) to rearrange the slabstones so the new slabstone can be placed in the garden. If the new slabstone cannot be placed in the garden no matter how the slabstones are rearranged, print −1-1.

Constraints

  • 1≤n≤20001 \le n \le 2000
  • 1≤d≤m≤1091 \le d \le m \le 10^9
  • 1≤x≤m≤1091 \le x \le m \le 10^9
  • 1≤li≤ri≤m1 \le l_i \le r_i \le m for i∈{1,2,…,n}i \in \{1, 2, \dots, n\}
  • ri+d+1≤li+1r_i + d + 1 \le l_{i+1} for i∈{1,2,…,n−1}i \in \{1, 2, \dots, n-1\}. The slabstones are given in order from left to right.

Examples3

  1. Example 1

    Input
    3 15 2 3
    2 4
    7 7
    12 13
    
    Expected output
    4
    
  2. Example 2

    Input
    5 100 1 75
    2 3
    5 7
    11 13
    17 19
    23 29
    
    Expected output
    9
    
  3. Example 3

    Input
    1 100 99 1
    1 1
    
    Expected output
    -1