#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define mid ((l+r) >> 1)
const ll INF = 1e18;
int n, m, a[100100], b[100100], c[100100], d[100100];
ll t1[1200120], t2[1200120];
ll find(ll t[], int nl, int nr, int node = 1, int l = 1, int r = m) {
if(r < nl || nr < l) return INF;
if(nl <= l && r <= nr) return t[node];
return min(find(t, nl, nr, node*2, l, mid), find(t, nl, nr, node*2+1, mid+1, r));
}
void update(ll t[], int id, ll val, int node = 1, int l = 1, int r = m) {
if(id < l || r < id) return;
if(l == r) {
t[node] = val;
return;
}
update(t, id, val, node*2, l, mid), update(t, id, val, node*2+1, mid+1, r);
t[node] = min(t[node*2], t[node*2+1]);
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin >> n >> m;
for(int i=1;i<=n;i++) cin >> a[i] >> b[i] >> c[i] >> d[i];
vector<int> X = {1, m};
for(int i=1;i<=n;i++) X.push_back(a[i]);
for(int i=1;i<=n;i++) X.push_back(b[i]);
for(int i=1;i<=n;i++) X.push_back(c[i]);
sort(X.begin(), X.end()), X.erase(unique(X.begin(), X.end()), X.end());
for(int i=1;i<=n;i++) a[i] = lower_bound(X.begin(), X.end(), a[i]) - X.begin() + 1;
for(int i=1;i<=n;i++) b[i] = lower_bound(X.begin(), X.end(), b[i]) - X.begin() + 1;
for(int i=1;i<=n;i++) c[i] = lower_bound(X.begin(), X.end(), c[i]) - X.begin() + 1;
m = X.size();
fill(t1, t1+m*4+1, INF), fill(t2, t2+m*4+1, INF);
update(t1, 1, 0), update(t2, m, 0);
ll ans = INF;
for(int i=1;i<=n;i++) {
auto L = find(t1, a[i], c[i]), R = find(t2, c[i], b[i]);
ans = min(ans, L+R+d[i]);
update(t1, c[i], L+d[i]);
update(t2, c[i], R+d[i]);
}
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... |