1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <bits/stdc++.h> #define ll long long #define FOR(i, l, r) for (ll i = l; i <= r; i++) #define FILE(x) freopen(x ".in", "r", stdin), freopen(x ".out", "w", stdout); #define pii pair<ll, ll> #define pll pair<long long, long long>
using namespace std; const ll N = 2e5 + 10, inf = 1e15; ll V, a, b, m, op[N], ans;
#define lc t[x << 1] #define rc t[x << 1 | 1] #define ls (x << 1) #define rs (x << 1 | 1) #define tx t[x]
struct node { ll l, r, val, mi1, mi2; } t[N << 2];
inline void pushup(ll x) { tx.val = min(lc.val, rc.val); tx.mi1 = min(lc.mi1, rc.mi1); tx.mi2 = min(lc.mi2, rc.mi2); }
void build(ll x, ll l, ll r) { tx.l = l, tx. r = r; if (l == r) { if (l == a) { tx.val = abs(op[1] - b); tx.mi1 = tx.val + a; tx.mi2 = tx.val - a; } else if(l == b) { tx.val = abs(op[1] - a); tx.mi1 = tx.val + b; tx.mi2 = tx.val - b; } else tx.val = tx.mi1 = tx.mi2 = inf; return; } ll mid = (l + r) >> 1; build(ls, l, mid); build(rs, mid + 1, r); pushup(x); }
void change(ll x, ll idx, ll now, ll w) { if (idx < tx.l || idx > tx.r) return; if (tx.l == idx && tx.r == idx) { tx.val = min(tx.val, w); tx.mi1 = min(tx.mi1, w + op[now - 1]); tx.mi2 = min(tx.mi2, w - op[now - 1]); return; } change(ls, idx, now, w); change(rs, idx, now, w); pushup(x); }
ll query(ll x, ll l, ll r, ll ty){ if (r < tx.l || tx.r < l) return inf; if (l <= tx.l && tx.r <= r) { if (ty == 0) return tx.val; else if (ty == 1) return tx.mi1; else if (ty == 2) return tx.mi2; else return inf; } return min(query(ls, l, r, ty), query(rs, l, r, ty)); }
int main() { #ifdef Clock clock_t Start_Time = clock(); #endif cin >> V >> m >> a >> b; for (ll i = 1; i <= m; i ++) cin >> op[i]; build(1, 1, V); for (ll i = 2; i <= m; i ++){ ans += abs(op[i] - op[i - 1]); ll w = min(query(1, 1, op[i], 2) + op[i], query(1, op[i], V, 1) - op[i]) - abs(op[i] - op[i - 1]); change(1, op[i - 1], i, w); } cout << query(1, 1, V, 0) + ans; #ifdef Clock cout << "\n- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\nRuntime: " << clock() - Start_Time << " ms\n"; system("pause"); #endif return 0; }
|