Advertisement
whiteshark05

Equalizing Array Element

Jun 1st, 2023
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | Software | 0 0
  1. import sys, bisect, collections, heapq, functools
  2. input = sys.stdin.readline
  3.  
  4.  
  5. rs = lambda: input().strip()
  6. ri = lambda: int(input())
  7. rmi = lambda: map(int, input().split())
  8. ra = lambda: [int(x) for x in input().split()]
  9.  
  10. INF = 10**18
  11. MOD = 10**9 + 7
  12.  
  13. def solve():
  14.     """
  15.    Divide each number in the array by d until 0
  16.    Use dict to save the number of steps to reach each smaller number
  17.    Use heap to keep only k smallest steps
  18.    Iterate through all smaller numbers and take global min step to reach them
  19.    """
  20.     freq = collections.defaultdict(list)
  21.     for x in A:
  22.         cnt = 0
  23.         while x:
  24.             heapq.heappush(freq[x], cnt)
  25.             cnt += 1
  26.             x //= d
  27.     ans = INF
  28.     for h in freq.values():
  29.         tmp = 0
  30.         if len(h) >= threshold:
  31.             t = threshold
  32.             while t:
  33.                 tmp += heapq.heappop(h)
  34.                 t -= 1
  35.             ans = min(ans, tmp)
  36.     return ans
  37.    
  38.        
  39. test_case = 1
  40. for _ in range(test_case):
  41.     threshold, d = 3, 2
  42.     A = [1,2,3,4,5]
  43.     print(solve())
  44.        
  45.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement