高级农民
- 积分
- 1277
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-11-15
- 最后登录
- 1970-1-1
|
貌似就是每次来两个新的 hub 就可以用新的 hub 抵消掉去到 hub 的 cost,
试了一下这个代码可以过截图的例子
- from typing import List
- class Solution:
- def get_min_connection_cost(
- self,
- n: int,
- ware_house_capacity: List[int],
- additional_hub_idices: List[List[int]]
- ) -> List[int]:
- """
- Without addiontal hub:
- total_cost = sum(cap[n - 1] - cap[i]) for i in range(len(n))
- With addiontal hub at index j:
- cost change of house k from cap[n - 1] - cap[k] to cap[j] - cap[k], net change is (cap[j] - cap[n - 1]), with house from 0 to j inclusive, which is (j + 1) * (cap[j] - cap[n - 1])
- With additional hub at index t ( j < t < n-1):
- net change is (cap[t] - cap[n - 1]) with repeatative of (t - j) * (cap[t] - cap[n - 1])
- Therefore for quick query, you can get sum of cap[n - 1] total first then use the math to do the calcualtion
- """
- res = []
- original_sum = 0
- for cap in ware_house_capacity:
- original_sum += ware_house_capacity[n - 1] - cap
- for k, j in additional_hub_idices:
- cost_change_pre_k = (k) * (ware_house_capacity[k - 1] - ware_house_capacity[n - 1])
- cost_change_between_k_and_j = (j - k) * (ware_house_capacity[j - 1] - ware_house_capacity[n - 1])
- res.append(original_sum + cost_change_pre_k + cost_change_between_k_and_j)
- return res
- def read_input_from_stdin():
- """
- Read input from stdin in the following format:
- - First line: size of caps array
- - Next n lines: elements of caps array
- - Next line: size of additional_house array
- - Next line: size of each sublist in additional_house
- - Next m lines: elements of additional_house sublists
-
- Returns:
- tuple: (n, caps, additional_house)
- """
- # Read size of caps array
- n = int(input().strip())
-
- # Read caps array
- caps = []
- for _ in range(n):
- caps.append(int(input().strip()))
-
- # Read size of additional_house array
- m = int(input().strip())
-
- # Read size of each sublist in additional_house (should be 2 for this problem)
- sublist_size = int(input().strip())
-
- # Read additional_house sublists
- additional_house = []
- for _ in range(m):
- # Read each pair of integers as a sublist
- sublist = list(map(int, input().strip().split()))
- # Ensure we only take the required number of elements
- additional_house.append(sublist[:sublist_size])
-
- return n, caps, additional_house
- if __name__ == '__main__':
- # Example with hardcoded values
- # n = 6
- # caps = [0, 2, 5, 9, 12, 18]
- # additional_house = [[2, 5], [1, 3]]
-
- # Read input from stdin
- n, caps, additional_house = read_input_from_stdin()
-
- # Get and print the result
- result = Solution().get_min_connection_cost(n, caps, additional_house)
- for r in result:
- print(r)
复制代码 |
|