Advertisement
pavel_777

3-E (cook potions)

Sep 8th, 2022 (edited)
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.72 KB | None | 0 0
  1. """
  2. Learning task
  3. https://contest.yandex.ru/contest/40146/problems/E/
  4.  
  5. Calculate the total utility of the `k` most useful potions (consisting of one or two ingredients)
  6.  
  7. I/O examples (first - n, k; the second - is the usefulness of `n` potions):
  8. 5 5
  9. -2 3 -5 5 1
  10. =
  11. 26
  12.  
  13. 2 1
  14. -1 1
  15. =
  16. 1
  17. """
  18.  
  19. import sys
  20. import bisect
  21.  
  22.  
  23. def main():
  24.     n, k = map(int, input().split())
  25.     line = sys.stdin.readline().rstrip()
  26.     a = list(map(int, line.split()))
  27.     a.sort()
  28.     a_sum = [0] + a.copy()
  29.     for i in range(1, len(a_sum)):
  30.         a_sum[i] = a_sum[i] + a_sum[i - 1]
  31.     if n == 1:
  32.         print(a[-1])
  33.         return
  34.  
  35.     def f(x, calc=False):
  36.         cur_idx = bisect.bisect_right(a, x)
  37.         res = n - min(cur_idx, n)
  38.         res_sum = 0
  39.         if calc:
  40.             res_sum = a_sum[-1] - a_sum[min(cur_idx, n)]
  41.         cur_r = len(a) - 1
  42.         for idx, v in enumerate(a):
  43.             cur_x = x - v
  44.             if a[-1] <= cur_x:
  45.                 continue
  46.             while cur_r > -1 and a[cur_r] > cur_x and cur_r > idx:
  47.                 cur_r -= 1
  48.             new_idx = max(cur_r, idx)
  49.             cur_res = n - new_idx - 1
  50.             res += cur_res
  51.             if calc:
  52.                 sum_part = a_sum[-1] - a_sum[min(new_idx+1, n)]
  53.                 temp_sum = sum_part + v * (n - new_idx - 1)
  54.                 res_sum += temp_sum
  55.         return res, res_sum
  56.  
  57.     l = min(a[0], a[0] + a[1]) - 1
  58.     r = max(2 * a[-1], 2 * sum(a[-2:])) + 1
  59.     while l < r:
  60.         x = (l + r) // 2
  61.         res_f, _ = f(x)
  62.         if res_f > k:
  63.             l = x + 1
  64.         else:
  65.             r = x
  66.  
  67.     cur_k, cur_sum = f(l, True)
  68.  
  69.     print(cur_sum + l * (k - cur_k))
  70.  
  71.  
  72. if __name__ == '__main__':
  73.     main()
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement