목차

수열과 쿼리 10

ps
링크acmicpc.net/…
출처BOJ
문제 번호13557
문제명수열과 쿼리 10
레벨플래티넘 1
분류

구간 쿼리

시간복잡도O(n+mlogn)
인풋사이즈n<=100,000, m<=100,000
사용한 언어Python
제출기록68948KB / 5460ms
최고기록5460ms
해결날짜2021/03/23

풀이

코드

"""Solution code for "BOJ 13557. 수열과 쿼리 10".

- Problem link: https://www.acmicpc.net/problem/13557
- Solution link: http://www.teferi.net/ps/problems/boj/13557
"""

import sys
from teflib import segmenttree


def merge(l, r):
    l_lmax, l_rmax, l_max, l_all = l
    r_lmax, r_rmax, r_max, r_all = r
    return (max(l_lmax, l_all + r_lmax), max(r_rmax, l_rmax + r_all),
            max(l_max, r_max, l_rmax + r_lmax), l_all + r_all)


def main():
    N = int(sys.stdin.readline())  # pylint: disable=unused-variable
    A = [int(x) for x in sys.stdin.readline().split()]
    segtree = segmenttree.SegmentTree(((x, x, x, x) for x in A), merge)
    M = int(sys.stdin.readline())
    for _ in range(M):
        x1, y1, x2, y2 = [int(x) for x in sys.stdin.readline().split()]
        if y1 <= x2:
            l_rmax = max(0, segtree.query(x1 - 1, y1 - 1)[1]) if x1 < y1 else 0
            m_all = segtree.query(y1 - 1, x2)[3]
            r_lmax = max(0, segtree.query(x2, y2)[0]) if x2 < y2 else 0
            print(l_rmax + m_all + r_lmax)
        else:
            l_rmax = max(0, segtree.query(x1 - 1, x2 - 1)[1]) if x1 < x2 else 0
            m_lmax, m_rmax, m_max, m_all = segtree.query(x2 - 1, y1)
            r_lmax = max(0, segtree.query(y1, y2)[0]) if y1 < y2 else 0
            print(max(l_rmax + m_lmax, 
                      m_rmax + r_lmax, 
                      l_rmax + m_all + r_lmax, 
                      m_max))


if __name__ == '__main__':
    main()