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
| #include <bits/stdc++.h> #define pre(u) node[u].l #define nxt(u) node[u].r #define val(u) node[u].val using namespace std;
const int maxn = 200005;
struct Node { int l, r, val; }node[maxn];
struct Heap { priority_queue<pair<int, int> > a, b; inline void push(pair<int, int> t) {a.push(t);} inline void pop() { while (b.size() && a.top() == b.top()) a.pop(), b.pop(); a.pop(); } inline void erase(pair<int, int> t) {b.push(t);} inline pair<int, int> top() { while (b.size() && a.top() == b.top()) a.pop(), b.pop(); return a.top(); } }q;
inline void del(int p) { nxt(pre(p)) = nxt(p); pre(nxt(p)) = pre(p); }
int N, M;
int main() { scanf("%d%d", &N, &M); if (M * 2 > N) return puts("Error!"), 0; for (register int i = 1; i <= N; ++i) scanf("%d", &node[i].val), node[i].l = i - 1, node[i].r = i + 1, q.push(make_pair(node[i].val, i)); node[1].l = N, node[N].r = 1; int ans = 0; for (register int i = 1; i <= M; ++i) { ans += q.top().first; int p = q.top().second; q.pop(); val(p) = val(pre(p)) + val(nxt(p)) - val(p); q.erase(make_pair(val(pre(p)), pre(p))), q.erase(make_pair(val(nxt(p)), nxt(p))); q.push(make_pair(val(p), p)); del(pre(p)), del(nxt(p)); } printf("%d", ans); return 0; }
|