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>
#define f0r(i,n) for(int i = 0;i<n;i++)
#define pb push_back
#define vll vector<long long int>
using namespace std;
typedef long long int ll;
ll mx[21][500005];
ll maxq(int x, int y){
//if(x <0 || y < 0 || x > y)return -1;
int len = y - x + 1;
int num = floor(log2(len));
return max(mx[num][x], mx[num][y - (int)pow(2,num) + 1]);
}
int main(){
ll n;
cin>>n;
vll v(n);
f0r(i,n)cin>>v[i];
int lg = floor(log2(n));
f0r(i, n){
mx[0][i] = v[i];
}
for(int i = 1;i<=lg;i++){
f0r(j, n - pow(2, i) + 1){
mx[i][j] = max(mx[i-1][j], mx[i-1][j + (int)pow(2, i-1)]);
}
}/*
f0r(i,lg+1){
f0r(j, n)cout<<mx[i][j]<<' ';
cout<<'\n';
}
*/
int q;
cin>>q;
while(q--){
int l,r;
cin>>l>>r;
l--;
r--;
int sz = r - l + 1;
int num = floor(log2(sz));
vector<pair<ll,ll>> w;
for(int i = l;i<=r;i++)w.pb({v[i], i});
sort(w.rbegin(), w.rend());
ll ans = 0;
f0r(i, num - 1){
for(int j = i+1;j<num;j++){
for(int k = j+1;k<num+1;k++){
vll temp = {w[i].second, w[j].second, w[k].second};
sort(temp.begin(), temp.end());
if(temp[1] - temp[0] <= temp[2]- temp[1]){
ans = max(ans, w[i].first + w[j].first + w[k].first);
}
}
}
}
f0r(ii, num + 2){
int i = w[ii].second;
//i at front
for(int j = i+1;j<=i + (r-i)/2; j++){
//range: j + j-i to r.
//cout<<maxq(j+j-i, r)<<' '<<w[ii].first<<' '<<v[j]<<'\n';
ans = max(ans, maxq(j+j-i, r) + w[ii].first + v[j]);
}
//i at back
for(int j = i-1;j>=i-(i-l)/2;j--){
//cout<<j-(i-j)<<' '<<j-1<<' '<<maxq(j-(i - j), j-1)<<'\n';
//cout<<maxq(j-(i - j), j-1)<<' '<<w[ii].first<<' '<<v[j]<<'\n';
ans = max(ans, maxq(j-(i - j), j-1) + w[ii].first + v[j]);
}
//i in middle
for(int j = i+1;j<=i+min(r-i,i-l);j++){
//cout<<maxq(i-(j-i),i-1)<<' '<<w[ii].first<<' '<<v[j]<<'\n';
ans = max(ans, maxq(i-(j-i),i-1) + w[ii].first + v[j]);
}
}
cout<<ans<<'\n';
}
}
# | 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... |