Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const int maxn = 2e5 + 10;
- typedef long long ll;
- int segment_tree[3 * maxn], a[maxn];
- int n;
- void build_tree(int L, int R, int pos) {
- if(L == R) {
- segment_tree[pos] = L;
- }
- else {
- int middle = (L + R) / 2;
- build_tree(L, middle, 2 * pos);
- build_tree(middle + 1, R, 2 * pos + 1);
- if(a[segment_tree[2 * pos]] > a[segment_tree[2 * pos + 1]]) {
- segment_tree[pos] = segment_tree[2 * pos + 1];
- }
- else {
- segment_tree[pos] = segment_tree[2 * pos];
- }
- }
- }
- int query(int L, int R, int pos, int i, int j) {
- // L R i L R j L R
- if(R < i or j < L) {
- return -1;
- }
- if(i <= L and R <= j) {
- return segment_tree[pos];
- }
- int middle = (L + R) / 2;
- int q1 = query(L, middle, 2 * pos, i, j);
- int q2 = query(middle + 1, R, 2 * pos + 1, i, j);
- if(q1 == -1) {
- return q2;
- }
- else if(q2 == -1) {
- return q1;
- }
- else if(a[q1] < a[q2]) {
- return q1;
- }
- return q2;
- }
- int rec(int i, int j) {
- int min_idx = query(0, n - 1, 1, i, j);
- int res = a[min_idx] * (j - i + 1);
- if(min_idx - 1 >= i) {
- res = max(res, rec(i, min_idx - 1));
- }
- if(min_idx + 1 <= j) {
- res = max(res, rec(min_idx + 1, j));
- }
- return res;
- }
- int main()
- {
- ios_base::sync_with_stdio(false);
- cin >> n;
- for(int i = 0; i < n; i++) {
- cin >> a[i];
- }
- build_tree(0, n - 1, 1);
- cout << rec(0, n - 1) << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement