#include "bits/stdc++.h"
using namespace std;
#define ln "\n"
#define pb push_back
#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define sz(x) ((int)(x).size())
#define int long long
const int MOD = 1e9 + 7;
const int inf = 1e18;
const int N = 1e5 + 7;
struct device {
	int a, b, c, d;
} a[N];
int n, m;
struct segtree {
	vector<int> st;
	int n;
	segtree() {}
	segtree(int n) : n(n) {
		st.resize(4 * n + 4, inf);
	}
	void update(int i, int l, int r, int u, int v) {
		if(l > u or r < u) return;
		if(l == r) {
			st[i] = min(st[i], v);
			return;
		}
		int m = (l + r) >> 1;
		update(i * 2, l, m, u, v);
		update(i * 2 + 1, m + 1, r, u, v);
		st[i] = min(st[i * 2], st[i * 2 + 1]);
	}
	int get(int i, int l, int r, int u, int v) {
		if(l > v or r < u) return inf * 2;
		if(u <= l and r <= v) {
			return st[i];
		}
		int m = (l + r) >> 1;
		return min(get(i * 2, l, m, u, v), get(i * 2 + 1, m + 1, r, u, v));
	}
	void update(int u, int x) {
		update(1, 1, n, u, x);
	}
	int get(int u, int v) {
		return get(1, 1, n, u, v);
	}
};
vector<int> vec;
int get_id(int x) {
	return lower_bound(all(vec), x) - vec.begin() + 1;
}
signed main() {
	cin.tie(0) -> sync_with_stdio(0);
	cin >> n >> m;
	for(int i = 1; i <= n; i++) {
		cin >> a[i].a >> a[i].b >> a[i].c >> a[i].d;
		vec.pb(a[i].a);
		vec.pb(a[i].b);
		vec.pb(a[i].c);
	}
	vec.pb(1);
	vec.pb(m);
	sort(all(vec));
	vec.erase(unique(all(vec)), vec.end());
	m = sz(vec);
	segtree s1 = segtree(m + 5), s2 = segtree(m + 5);
	s1.update(1, 0);
	s2.update(m, 0);
	int ans = inf;
	for(int i = 1; i <= n; i++) {
		a[i].a = get_id(a[i].a);
		a[i].b = get_id(a[i].b);
		a[i].c = get_id(a[i].c);
		int lef = s1.get(a[i].a, a[i].b);
		int rig = s2.get(a[i].a, a[i].b);
		ans = min(ans, lef + rig + a[i].d);
		s1.update(a[i].c, lef + a[i].d);
		s2.update(a[i].c, rig + a[i].d);
	}
	if(ans >= inf) ans = -1;
	cout << ans << ln;
    cerr << "\nTime: " << clock() * 1000 / CLOCKS_PER_SEC;
}	
| # | 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... |