description: You are given n segments on a number line, numbered from 1 to n. The i-th segments covers all integer points from l_i to r_i and has a value w_i.
  
  You are asked to select a subset of these segments (possibly, all of them). Once the subset is selected, it's possible to travel between two integer points if there exists a selected segment that covers both of them. A subset is good if it's possible to reach point m starting from point 1 in arbitrary number of moves.
  
  The cost of the subset is the difference between the maximum and the minimum values of segments in it. Find the minimum cost of a good subset.
  
  In every test there exists at least one good subset.
  
  Input
  
  The first line contains two integers n and m (1 ≤ n ≤ 3 ⋅ 10^5; 2 ≤ m ≤ 10^6) — the number of segments and the number of integer points.
  
  Each of the next n lines contains three integers l_i, r_i and w_i (1 ≤ l_i < r_i ≤ m; 1 ≤ w_i ≤ 10^6) — the description of the i-th segment.
  
  In every test there exists at least one good subset.
  
  Output
  
  Print a single integer — the minimum cost of a good subset.
  
  Examples
  
  Input
  
  
  5 12
  1 5 5
  3 4 10
  4 10 6
  11 12 5
  10 12 3
  
  
  Output
  
  
  3
  
  
  Input
  
  
  1 10
  1 10 23
  
  
  Output
  
  
  0
solution: #include <bits/stdc++.h>
  using namespace std;
  const int maxn = 5e5 + 7;
  int n, m;
  typedef struct Edge {
    int l, r, w;
  } Edge;
  bool cmp(Edge a, Edge b) { return a.w < b.w; }
  Edge eg[maxn];
  int tot = 0;
  int uni[maxn * 2];
  int t[maxn << 3];
  int lazy[maxn << 3];
  void pushDown(int k);
  void update(int k, int l, int r, int x, int y, int v);
  int main() {
    ios::sync_with_stdio(0);
    cout.tie(0);
    cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
      cin >> eg[i].l >> eg[i].r >> eg[i].w;
    }
    m--;
    sort(eg + 1, eg + 1 + n, cmp);
    int p, q;
    p = q = 1;
    int ans = 1e9;
    update(1, 1, m, eg[q].l, eg[q].r - 1, 1);
    while (p <= q && q <= n) {
      while (t[1] >= 1 && p <= q) {
        ans = min(ans, eg[q].w - eg[p].w);
        update(1, 1, m, eg[p].l, eg[p].r - 1, -1);
        p++;
      }
      q++;
      if (q > n) break;
      update(1, 1, m, eg[q].l, eg[q].r - 1, 1);
    }
    if (ans == 1e9)
      cout << -1;
    else
      cout << ans;
  }
  void update(int k, int l, int r, int x, int y, int v) {
    if (x <= l && r <= y) {
      t[k] += v;
      lazy[k] += v;
    } else {
      pushDown(k);
      int mid = (l + r) / 2;
      if (x <= mid) update(k * 2, l, mid, x, y, v);
      if (y > mid) update(k * 2 + 1, mid + 1, r, x, y, v);
      t[k] = min(t[k * 2 + 1], t[k * 2]);
    }
  }
  void pushDown(int k) {
    if (lazy[k]) {
      lazy[k << 1] += lazy[k];
      lazy[k << 1 | 1] += lazy[k];
      t[k << 1] += lazy[k];
      t[k << 1 | 1] += lazy[k];
      lazy[k] = 0;
    }
  }
  