#include <bits/stdc++.h>
#define endl '\n'
#define int long long
#define fi first
#define se second
#define pb push_back
using namespace std;
const int maxn = 3e5 + 5, inf = 1e15 + 1;
struct segment{
    int st[4*maxn+5];
    segment(){
        fill_n(st, 4 * maxn + 5, inf);
    }
    void update(int id, int l, int r, int k, int val){
        if (l > r) return;
        if (l == r){
            st[id] = min(st[id], val);
            return;
        }
        int mid = (l + r) / 2; // Avoid potential overflow
        if (k <= mid) {
            update(id*2, l, mid, k, val);
        } else {
            update(id*2+1, mid+1, r, k, val);
        }
        st[id] = min(st[id*2], st[id*2+1]);
    }
    int get(int id, int l, int r, int ul, int ur){
        if (l > ur || r < ul) return inf;
        if (ul <= l && r <= ur) return st[id];
        
        int mid = (l + r) / 2;
        return min(get(id*2, l, mid, ul, ur), get(id*2+1, mid+1, r, ul, ur));
    }
};
 
segment l, r;
signed main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n, q;
    cin >> q >> n;
    int ans = inf;
    l.update(1, 1, n, 1, 0);
    r.update(1, 1, n, n, 0);
    while(q--){
        int ul, ur, k, val;
        cin >> ul >> ur >> k >> val;
        ans = min(ans, l.get(1, 1, n, ul, k) + r.get(1, 1, n, k, ur) + val);
        // dpl[pos] = min(min(l -> k)dpl[] + val, dpl[pos]);
        int newL = min(l.get(1, 1, n, ul, k) + val, l.get(1, 1, n, k, k));
        l.update(1, 1, n, k, newL);
        // same with right
        int newR = min(r.get(1, 1, n, k, ur) + val, r.get(1, 1, n, k, k));
        r.update(1, 1, n, k, newR);
    }
    cout << (ans >= inf ? -1 : ans);
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |