Bulbo

Bananistan is a beautiful banana republic. Beautiful women in beautiful dresses. Beautiful statues of beautiful warlords. Beautiful stars in beautiful nights.

In Bananistan people play this crazy game – Bulbo. There’s an array of bulbs and player at the position, which represents one of the bulbs. The distance between two neighboring bulbs is 1. Before each turn player can change his position with cost |pos new - pos old|. After that, a contiguous set of bulbs lights-up and player pays the cost that’s equal to the distance to the closest shining bulb. Then, all bulbs go dark again. The goal is to minimize your summed cost. I tell you, Bananistanians are spending their nights playing with bulbs.

Banana day is approaching, and you are hired to play the most beautiful Bulbo game ever. A huge array of bulbs is installed, and you know your initial position and all the light-ups in advance. You need to play the ideal game and impress Bananistanians, and their families.

Input

The first line contains number of turns n and initial position x. Next n lines contain two numbers l start and l end, which represent that all bulbs from interval [l start, l end] are shining this turn.

  • 1 ≤ n ≤ 5000
  • 1 ≤ x ≤ 109
  • 1 ≤ l start ≤ l end ≤ 109

Output

Output should contain a single number which represents the best result (minimum cost) that could be obtained by playing this Bulbo game.

Examples

input

5 4
2 7
9 16
8 10
9 17
1 6

output

8

Note

Before 1. turn move to position 5

Before 2. turn move to position 9

Before 5. turn move to position 8

Solution:

#include <bits/stdc++.h>

using namespace std;

const int N = 10010;

long long cost[N], new_cost[N];
int x[N], y[N];

int main() {
int n, start;
scanf("%d %d", &n, &start);
vector <int> pos;
pos.push_back(start);
for (int i = 0; i < n; i++) {
    scanf("%d %d", x + i, y + i);
    pos.push_back(x[i]);
    pos.push_back(y[i]);
  }
  sort(pos.begin(), pos.end());
  int cnt = pos.size();
  for (int i = 0; i < cnt; i++) {
    cost[i] = abs(pos[i] - start);
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < cnt; j++) {
      new_cost[j] = cost[j] + (pos[j] < x[i] ? (x[i] - pos[j]) : 0) + (pos[j] > y[i] ? (pos[j] - y[i]) : 0);
}
for (int j = 0; j + 1 < cnt; j++) {
      if (pos[j] < x[i] && new_cost[j] < new_cost[j + 1]) {
        new_cost[j + 1] = new_cost[j];
      }
    }
    for (int j = cnt - 1; j >= 0; j--) {
if (pos[j] > y[i] && new_cost[j] < new_cost[j - 1]) {
        new_cost[j - 1] = new_cost[j];
      }
    }
    for (int j = 0; j < cnt; j++) {
      cost[j] = new_cost[j];
    }
  }
  long long ans = cost[0];
  for (int j = 1; j < cnt; j++) {
    ans = min(ans, cost[j]);
  }
  cout << ans << endl;
  return 0;
}