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
| #include <cstdio> #include <queue> using namespace std; template <class Type> void read(Type &x) { char c; bool flag = false; while ((c = getchar()) < '0' || c > '9') c == '-' && (flag = true); x = c - '0'; while ((c = getchar()) >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0'; if (flag) x = ~x + 1; } template <class Type, class ...rest> void read(Type &x, rest &...y) { read(x), read(y...); } template <class Type> void write(Type x) { if (x < 0) putchar('-'), x = ~x + 1; if (x > 9) write(x / 10); putchar(x % 10 + '0'); } typedef long long LL; const int N = 5e5 + 10, M = 20; int n, m, L, R, s[N]; int lg[N], st[N][M]; int smin (int a, int b) { return s[a] > s[b] ? a : b; } void init() { for (int i = 2; i <= n; ++i) lg[i] = lg[i >> 1] + 1; for (int i = 1; i <= n; ++i) st[i][0] = i; for (int k = 1; 1 << k <= n; ++k) for (int i = 1; i + (1 << k) - 1 <= n; ++i) st[i][k] = smin(st[i][k - 1], st[i + (1 << k - 1)][k - 1]); } int query (int a, int b) { int k = lg[b - a + 1]; return smin(st[a][k], st[b - (1 << k) + 1][k]); } struct Data { int a, b, l, r; Data (int _a, int _b, int _l, int _r) : a(_a), b(_b), l(_l), r(_r) {} int calc () const { return s[r] - s[l - 1]; } bool operator < (const Data &_) const { return calc() < _.calc(); } }; int main () { read(n, m, L, R); for (int i = 1; i <= n; ++i) read(s[i]), s[i] += s[i - 1]; init(); priority_queue <Data> q; for (int i = 1; i + L - 1 <= n; ++i) { int t = min(i + R - 1, n); q.emplace(i + L - 1, t, i, query(i + L - 1, t)); } LL res = 0; while (m--) { Data t = q.top(); q.pop(); res += t.calc(); if (t.r - 1 >= t.a) q.emplace(t.a, t.r - 1, t.l, query(t.a, t.r - 1)); if (t.r + 1 <= t.b) q.emplace(t.r + 1, t.b, t.l, query(t.r + 1, t.b)); } write(res); return 0; }
|