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;
  constexpr int N = 3e5, M = 1e6, max_size = 1 << 21;
  int t[max_size], inc[max_size];
  struct STOperation {
    int mod, l, r;
    int call(int i = 0, int L = 0, int R = M) {
      int dummy = 1e9, &maybe = !mod ? dummy : t[i];
      if (R <= l || r <= L) {
        return maybe + inc[i];
      } else if (l <= L && R <= r) {
        inc[i] += mod;
        return t[i] + inc[i];
      }
      return (maybe = min(call(2 * i + 1, L, (L + R) / 2),
                          call(2 * i + 2, (L + R) / 2, R))) +
             inc[i];
    }
  };
  pair<int, pair<int, int>> s[N];
  int main() {
    cin.tie(0), ios::sync_with_stdio(0);
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
      cin >> s[i].second.first >> s[i].second.second >> s[i].first,
          --s[i].second.first, --s[i].second.second;
    }
    sort(s, s + n);
    int l = 0, r = 0, ans = 1e9;
    while (1) {
      if (STOperation{0, 0, m - 1}.call()) {
        ans = min(ans, s[r - 1].first - s[l].first);
        STOperation{-1, s[l].second.first, s[l].second.second}.call();
        ++l;
      } else if (r == n) {
        break;
      } else {
        STOperation{1, s[r].second.first, s[r].second.second}.call();
        ++r;
      }
    }
    cout << ans << '\n';
    return 0;
  }
  