#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define ff first
#define ss second
#define all(s) s.begin(),s.end()
#define rall(s) s.rbegin(),s.rend()
struct segtree{
    vector<ll>d;
    segtree(ll n){
        d.resize(4*n);
        fill(all(d),(ll)1e18);
    }
    ll query(ll v,ll l,ll r,ll L,ll R){
        if(R<L||R<l||r<L) return (ll)1e18;
        if(L<=l&&r<=R){
            return d[v];
        }
        ll m=(l+r)>>1;
        return min(query(v<<1,l,m,L,R),query(v<<1|1,m+1,r,L,R));
    }
    void update(ll v,ll l,ll r,ll pos,ll val){
        if(r<pos||pos<l) return;
        if(l==r){
            d[v]=val;
            return;
        }
        ll m=(l+r)>>1;
        update(v<<1,l,m,pos,val);
        update(v<<1|1,m+1,r,pos,val);
        d[v]=min(d[v<<1],d[v<<1|1]);
    }
};
int main(){
    ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    ll n,m;
    cin>>n>>m;
    ll a[n+5],b[n+5],c[n+5],d[n+5];
    vector<ll>v;
    v.pb(1);
    v.pb(m);
    for(ll i=1;i<=n;i++){
        cin>>a[i]>>b[i]>>c[i]>>d[i];
        v.pb(a[i]);
        v.pb(b[i]);
        v.pb(c[i]);
    }
    sort(all(v));
    v.erase(unique(all(v)),v.end());
    ll dp[n+5][2];
    for(ll i=1;i<=n;i++){
        a[i]=lower_bound(all(v),a[i])-v.begin();
        b[i]=lower_bound(all(v),b[i])-v.begin();
        c[i]=lower_bound(all(v),c[i])-v.begin();
    }
    ll sz=v.size();
    segtree sg1(sz);
    sg1.update(1,0,sz-1,0,0);
    dp[0][0]=0;
    for(ll i=1;i<=n;i++){
        dp[i][0]=sg1.query(1,0,sz-1,a[i],b[i])+d[i];
        sg1.update(1,0,sz-1,c[i],dp[i][0]);
    }
    segtree sg2(sz);
    sg2.update(1,0,sz-1,sz-1,0);
    dp[0][1]=0;
    for(ll i=1;i<=n;i++){
        dp[i][1]=sg2.query(1,0,sz-1,a[i],b[i])+d[i];
        sg2.update(1,0,sz-1,c[i],dp[i][1]);
    }
    ll ans=(ll)1e18;
    for(ll i=1;i<=n;i++){
        ans=min(ans,dp[i][0]+dp[i][1]-d[i]);
    }
    if(ans==(ll)1e18) ans=-1;
    cout<<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... |