This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const int mod = 1e9 + 7;
const int LOG = 20;
const int maxn = 1e5 + 5;
struct SegTree {
int n, h;
vector<ll> tree, lazy;
SegTree(int _n) {
n = _n;
h = sizeof(int) * 8 - __builtin_clz(n);
tree.resize(2*n+5);
lazy.resize(n+5);
}
void apply(int p, ll v) {
tree[p] += v;
if(p < n) lazy[p] += v;
}
void build(int p) {
while(p > 1) {
p >>= 1;
tree[p] = min(tree[p<<1], tree[p<<1|1]) + lazy[p];
}
}
void push(int p) {
for(int s=h; s; --s) {
int i = p >> s;
if(lazy[i]) {
apply(i<<1, lazy[i]);
apply(i<<1|1, lazy[i]);
lazy[i] = 0;
}
}
}
void update(int l, int r, ll v) {
l+=n, r+=n;
int l0=l, r0=r;
for(; l<r; l>>=1, r>>=1) {
if(l&1) apply(l++, v);
if(r&1) apply(--r, v);
}
build(l0); build(r0-1);
}
ll query(int l, int r) {
ll ans1 = 1e12, ans2 = 1e12;
l+=n, r+=n;
push(l); push(r-1);
for(; l<r; l>>=1, r>>=1) {
if(l&1) ans1 = min(ans1, tree[l++]);
if(r&1) ans2 = min(ans2, tree[--r]);
}
return min(ans1, ans2);
}
void reset() {
for(auto &x : tree) x = 0;
for(auto &x : lazy) x = 0;
}
};
ll dp[maxn][105], v[maxn];
signed main() {
ios_base::sync_with_stdio(false);
cout.tie(0); cin.tie(0);
int n, k;
cin >> n >> k;
for(int i=0; i<=n; i++)
for(int j=0; j<=k; j++) dp[i][j] = 1e9;
for(int i=1; i<=n; i++) cin >> v[i];
dp[0][0] = 0;
ll mx = 0;
for(int i=1; i<=n; i++) {
mx = max(mx, v[i]);
dp[i][1] = mx;
}
SegTree tree(n+1);
for(int j=2; j<=k; j++) {
vector<pii> st; st.push_back({ 1e9, 0 });
int SZ = 1;
for(int i=1; i<=n; i++) {
int last = st.back().second;
while(SZ && st.back().first <= v[i]) {
if(SZ > 1) tree.update(st[SZ-2].second+1, st[SZ-1].second+1, v[i]-st.back().first);
st.pop_back();
SZ--;
}
st.push_back({ v[i], i }); SZ++;
tree.update(last+1, st.back().second+1, v[i]);
tree.update(i, i+1, dp[i-1][j-1]);
dp[i][j] = tree.query(1, i+1);
}
tree.reset();
}
cout << dp[n][k] << '\n';
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |