이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
// TODO implement optimally
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <utility>
#include <algorithm>
#include <cmath>
int x, q;
int arr[500005];
int sp_tb[19][500005];
void build_sparse_table() {
for (int l = 1; l < 19; l++) {
for (int i = 1; i+(1<<l)-1 <= x; i++) {
sp_tb[l][i] = std::max(sp_tb[l-1][i],sp_tb[l-1][i+(1<<(l-1))]);
}
}
}
int max_query(int l, int r) {
int lvl = 31-__builtin_clz(r-l+1);
return std::max(sp_tb[lvl][l], sp_tb[lvl][r-(1<<lvl)+1]);
}
struct PQComp {
bool operator() (int a, int b) {
return arr[a] < arr[b];
}
};
// take the 2 maxes, let their positions be 1 and 2
// therefore we have the following cases
//
// 1: ---1##--2
// 2: --###1--2
// 3: -1-2-####
int query(int l, int r) {
if (r-l+1<=7) {
int ret = 0;
for (int i = l; i <= r; i++) {
for (int j = i+1; j <= r; j++) {
if (j+(j-i)>r) {
break;
}
ret = std::max(ret, arr[i]+arr[j]+max_query(j+(j-i),r));
}
}
return ret;
}
std::priority_queue<int, std::vector<int>, PQComp> pq;
for (int i = l; i <= r; i++) {
pq.emplace(i);
}
std::vector<int> pos;
while (!pq.empty()&&pos.size()<10) {
int k = pq.top();
pq.pop();
pos.emplace_back(k);
}
int ret = 0;
for (auto m1 : pos) {
for (auto m2 : pos) {
if (m1==m2) {
continue;
}
if (m1>m2) std::swap(m1,m2);
int le, ri;
// 1
if (m1+1<m2) {
le = m1+1;
ri = (m1+m2)/2;
ret = std::max(ret,arr[m1]+arr[m2]+max_query(le,ri));
}
// 2
if (m1-1>=l) {
le = std::max(l,m1-(m2-m1));
ri = m1-1;
ret = std::max(ret,arr[m1]+arr[m2]+max_query(le,ri));
}
// 3
if (m2+(m2-m1)<=r) {
le = m2+(m2-m1);
ri = r;
ret = std::max(ret,arr[m1]+arr[m2]+max_query(le,ri));
}
}
}
return ret;
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(NULL);
std::cin >> x;
for (int i = 1; i <= x; i++) {
std::cin >> arr[i];
sp_tb[0][i] = arr[i];
}
build_sparse_table();
std::cin >> q;
while (q--) {
int l, r;
std::cin >> l >> r;
std::cout << query(l,r) << "\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... |