This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
* Author : shora
*/
#include <bits/stdc++.h>
#define print(_v) for (auto &_ : _v) {cerr << _ << ' ';} cerr << endl;
using namespace std;
using ll = long long;
const int oo = 1e9;
const int N = 1e5;
int n, k;
int a[N+1], spt[N+1][20], log_2[N+1];
int get(int l, int r) {
int e = log_2[r - l + 1];
// [0, 10] = [0, 7], [3, 10]
int x = a[spt[l][e]] - a[spt[l][e] + 1];
int y = a[spt[r - (1 << e) + 1][e]] - a[spt[r - (1 << e) + 1][e] + 1];
if (x < y)
return spt[l][e];
else
return spt[r - (1 << e) + 1][e];
}
int h(int l, int r) {
if (l == r)
return oo;
int m = get(l, r-1);
int res = a[m] - a[l] + 1 + a[r] - a[m+1] + 1 - (a[r] - a[l] + 1);
return res;
}
struct S {
int l, r;
S(int l, int r): l(l), r(r) {}
friend bool operator < (const S& u, const S& v) {
return h(u.l, u.r) > h(v.l, v.r);
}
friend ostream& operator << (ostream& os, const S& s) {
os << '[' << s.l << ", " << s.r << ']';
}
};
void build() {
for (int i = 2; i <= n; ++i)
log_2[i] = log_2[i / 2] + 1;
for (int i = 1; i < n; ++i)
spt[i][0] = i;
for (int j = 1; j <= log_2[n]; ++j) {
for (int i = 1; i + (1 << j) - 1 < n; ++i) {
// [0, 7] = [0, 3] [4, 7]
int x = a[spt[i][j-1]] - a[spt[i][j-1] + 1];
int y = a[spt[i + (1 << (j-1))][j-1]] - a[spt[i + (1 << (j-1))][j-1] + 1];
if (x < y)
spt[i][j] = spt[i][j-1];
else
spt[i][j] = spt[i + (1 << (j-1))][j-1];
}
}
}
int main() {
cin.tie(0)->sync_with_stdio(0); cout.tie(0);
cin >> n >> k;
for (int i = 1; i <= n; ++i)
cin >> a[i];
build();
priority_queue<S> q;
q.push(S(1, n));
int cur = a[n] - a[1] + 1, res = cur;
for (int i = 2; i <= k; ++i) {
S s = q.top(); q.pop();
int l = s.l, r = s.r;
res -= a[r] - a[l] + 1;
// tim m thuoc [l, r-1] minimize a[m]-a[l]+1 + a[r] - a[m+1]+1
// <> minimize a[m]-a[m+1]
int m = get(l, r-1);
res += a[m] - a[l] + 1;
res += a[r] - a[m+1] + 1;
q.push(S(l, m));
q.push(S(m+1, r));
}
cout << res;
return 0;
}
Compilation message (stderr)
stove.cpp: In function 'std::ostream& operator<<(std::ostream&, const S&)':
stove.cpp:37:2: warning: no return statement in function returning non-void [-Wreturn-type]
37 | }
| ^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |