ps | |
---|---|
링크 | acmicpc.net/… |
출처 | BOJ |
문제 번호 | 28031 |
문제명 | Milk Sum |
레벨 | 골드 2 |
분류 |
누적합, 이분탐색 |
시간복잡도 | O((n+q)logn) |
인풋사이즈 | n<=1.5*10^5, q<=1.5*10^5 |
사용한 언어 | Python 3.11 |
제출기록 | 51204KB / 736ms |
최고기록 | 736ms |
해결날짜 | 2023/07/24 |
"""Solution code for "BOJ 28031. Milk Sum".
- Problem link: https://www.acmicpc.net/problem/28031
- Solution link: http://www.teferi.net/ps/problems/boj/28031
Tags: [prefix sum] [binary search]
"""
import bisect
import sys
def main():
N = int(sys.stdin.readline()) # pylint: disable=unused-variable
a = [int(x) for x in sys.stdin.readline().split()]
sorted_cows = sorted(a)
prefix_sum = [v := 0] + [v := v + x for x in sorted_cows]
total_milk = sum(i * x for i, x in enumerate(sorted_cows, start=1))
Q = int(sys.stdin.readline())
for _ in range(Q):
i, j = [int(x) for x in sys.stdin.readline().split()]
cur_milk, next_milk = a[i - 1], j
cur_pos = bisect.bisect_left(sorted_cows, cur_milk)
next_pos = (
bisect.bisect_left(sorted_cows, j)
if next_milk <= cur_milk
else bisect.bisect_right(sorted_cows, j) - 1
)
answer = (
total_milk - cur_milk * (cur_pos + 1) + next_milk * (next_pos + 1)
)
if next_pos > cur_pos:
answer -= prefix_sum[next_pos + 1] - prefix_sum[cur_pos + 1]
else:
answer += prefix_sum[cur_pos] - prefix_sum[next_pos]
print(answer)
if __name__ == '__main__':
main()