This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int len = 1e5+5;
const ll inf = 1e18;
int lef[len], rig[len], pos[len], cost[len];
ll dp[len][3];
struct node{
    ll mn0, mn1;
    node *left, *right;
    node(ll m0 = inf, ll m1 = inf, node *l = NULL, node *r = NULL){
        mn0 = m0;
        mn1 = m1;
        left = l;
        right = r;
    }
};
typedef node* pnode;
pnode null = new node(), root = new node();
void upd(pnode &t, int l, int r, int i, ll m0, ll m1){
    if (t == null)
        t = new node(m0, m1, null, null);
    t->mn0 = min(t->mn0, m0);
    t->mn1 = min(t->mn1, m1);
    if (l == r)
        return;
    int mid = (l+r)/2;
    if (i <= mid)
        upd(t->left, l, mid, i, m0, m1);
    else
        upd(t->right, mid+1, r, i, m0, m1);
}
node join(node a, node b){
    node c;
    c.mn0 = min(a.mn0, b.mn0);
    c.mn1 = min(a.mn1, b.mn1);
    return c;
}
node ask(pnode t, int l, int r, int i, int j){
    if (r < i || j < l)
        return node();
    if (i <= l && r <= j)
        return *t;
    int mid = (l+r)/2;
    return join(ask(t->left, l, mid, i, j), ask(t->right, mid+1, r, i, j));
}
int main(){
    int n, m;
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d %d %d %d", &lef[i], &rig[i], &pos[i], &cost[i]);
    null->left = null->right = root = null;
    ll ans = inf;
    for (int i = 1; i <= n; i++){
        ll d0 = ask(root, 1, m, lef[i], rig[i]).mn0+cost[i];
        ll d1 = ask(root, 1, m, lef[i], rig[i]).mn1+cost[i];
        if (lef[i] == 1 && rig[i] == m)
            d0 = d1 = cost[i];
        else if (lef[i] == 1)
            d0 = cost[i];
        else if (rig[i] == m)
            d1 = cost[i];
        ans = min(ans, d0+d1-cost[i]);
        upd(root, 1, m, pos[i], d0, d1);
    }
    if (ans == inf)
        printf("-1\n");
    else
        printf("%lld", ans);
    return 0;
}
Compilation message (stderr)
pinball.cpp: In function 'int main()':
pinball.cpp:61:10: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
     scanf("%d %d", &n, &m);
     ~~~~~^~~~~~~~~~~~~~~~~
pinball.cpp:63:14: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
         scanf("%d %d %d %d", &lef[i], &rig[i], &pos[i], &cost[i]);
         ~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| # | 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... |