#include #include #include #include #include using namespace std; using ll = long long; template using grid = vector>; #define REP(i,n) for(ll i=0;i<(ll)(n);i++) #define REPD(i,n) for(ll i=n-1;i>=0;i--) #define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++) #define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--) #define input(...) __VA_ARGS__; in(__VA_ARGS__) void print() { std::cout << std::endl; } template void print(Head&& head, Tail&&... tail) { std::cout << head << " "; print(std::forward(tail)...); } void in() { } template void in(Head&& head, Tail&&... tail) { cin >> head; in(std::forward(tail)...); } #define NEUTRAL LLONG_MAX #define OP min class SegTree { public: int t = 1; vector table; SegTree(int n) { while (t <= n) { t *= 2; } table = vector(t * 2 - 1, NEUTRAL); } int up(int node) { return (node - 1) / 2; } int down(int node) { return (node * 2) + 1; } void update(int i, long long x) { i += t - 1; table[i] = x; while (i != 0) { i = up(i); int c = down(i); table[i] = OP(table[c], table[c + 1]); } } long long find(int l, int r, int node=0, int sl=0, int sr=-1) { if (sr < 0) sr = t; if (sr <= l || r <= sl) { return NEUTRAL; } if (l <= sl && sr <= r) { return table[node]; } int sc = (sl + sr) / 2; int c = down(node); return OP(find(l, r, c, sl, sc), find(l, r, c + 1, sc, sr)); } }; int main() { ll input(n); vector y(n); REP(i, n) cin >> y[i]; ll YMAX = 1000; vector> table(n + 1); REP(i, n + 1) { if (i == n) table[i] = vector(YMAX + 1, 0); else table[i] = vector(YMAX + 1); } REPD(i, n) { SegTree seg(YMAX + 1); FOR(j, 0, YMAX) { seg.update(j, table[i + 1][j] + abs(y[i] - j)); } FORD(h, YMAX, 0) { table[i][h] = seg.find(h, YMAX + 1); } } print(table[0][0]); }