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 "meetings.h"
#include <bits/stdc++.h>
#define pb push_back
#define f first
#define sc second
using namespace std;
typedef long long int ll;
typedef string str;
struct segtree{
int k;
vector<int> mx;
segtree(int n){
k = 1;
while(k < n) k*=2;
mx.assign(2*k, 0);
}
void update(int i, int x){
i+=k;
mx[i] = x;
i/=2;
while(i){
mx[i] = max(mx[2*i], mx[2*i+1]);
i/=2;
}
}
int get(int l, int r, int nd, int a, int b){
if(a > r || b < l) return 0;
if(a >= l && b <= r) return mx[nd];
int md = (a+b)/2;
return max(get(l, r, 2*nd, a, md), get(l, r, 2*nd+1, md+1, b));
}
int get(int l, int r){
return get(l, r, 1, 0, k-1);
}
};
vector<ll> minimum_costs_subtask_nq(const vector<int>& _H, const vector<int>& L, const vector<int>& R){
vector<ll> H;
int n = _H.size(), q = L.size();
for(int i = 0; i < n; i++) H.pb(_H[i]);
vector<ll> ans(q);
for(int qi = 0; qi < q; qi++){
int l = L[qi], r = R[qi];
vector<ll> costs(r-l+1, 0);
stack<pair<ll, int>> st;
ll c = 0;
for(int i = l; i <= r; i++){
while(!st.empty() && st.top().f <= H[i]){
auto [h, j] = st.top();
st.pop();
if(st.empty()) c-=h*(j-l+1);
else c-=h*(j-st.top().sc);
}
if(st.empty()) c+=H[i]*(i-l+1);
else c+=H[i]*(i-st.top().sc);
st.push({H[i], i});
costs[i-l]+=c;
}
while(!st.empty()) st.pop();
c = 0;
for(int i = r; i >= l; i--){
while(!st.empty() && st.top().f <= H[i]){
auto [h, j] = st.top();
st.pop();
if(st.empty()) c-=h*(r-j+1);
else c-=h*(st.top().sc-j);
}
if(st.empty()) c+=H[i]*(r-i+1);
else c+=H[i]*(st.top().sc-i);
st.push({H[i], i});
costs[i-l]+=c;
costs[i-l]-=H[i];
}
ans[qi] = *min_element(costs.begin(), costs.end());
}
return ans;
}
vector<ll> minimum_costs(vector<int> H, vector<int> L, vector<int> R){
int n = H.size(), q = L.size();
if(n <= 5000 && q <= 5000) return minimum_costs_subtask_nq(H, L, R);
vector<int> left(n, 0), right(n, 0);
segtree seg(n);
for(int i = 0; i < n; i++) if(H[i] == 1) {
left[i] = 1;
if(i) left[i]+=left[i-1];
seg.update(i, left[i]);
}
for(int i = n-1; i >= 0; i--) if(H[i] == 1){
right[i] = 1;
if(i+1 < n) right[i]+=right[i+1];
}
vector<ll> ans(q, 0);
for(int qi = 0; qi < q; qi++){
int l = L[qi], r = R[qi];
if(right[l] >= r-l+1){
ans[qi] = r-l+1;
continue;
}
int a = right[l], b = left[r];
ans[qi] = 2*(r-l+1)-max(max(a, b), seg.get(l+a, r-b));
}
return ans;
}
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |