[leetcode] 1029.2つの都市のスケジューリング

説明

ある会社が2n人にインタビューすることを計画しています。cost [i] = [aCosti、bCosti]の配列コストを考えると、i番目の人を都市aに飛ばすコストはaCostiであり、i番目の人を都市bに飛ばすコストはbCostiです。

正確にn人が各都市に到着するように、すべての人を都市に飛ばすための最小コストを返します。

例1:

Input: costs = [[10,20],[30,200],[400,50],[30,20]]
Output: 110
Explanation: 
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.

例2:

Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859

例3:

Input: costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
Output: 3086

制約:

  • 2 * n == cost.length
  • 2 <= cost.length <= 100
  • cost.lengthは偶数です。
  • 1 <= aCosts、bCosts <= 1000

分析

質問の意味は次のとおりです。2n人がいて、配列のi番目の項目は、都市aに行くi番目の人のコストaCostiと都市bに行くコストbCostiを表し、配列で表されます。

私は答えのアイデアを参照します、それは非常に賢いです:

  • aCosti-bCostiで最小から最大に並べ替えます。
  • 最初のn人を都市Aに飛ばし、残りを都市Bに飛ばして、総費用を計算します。

アイデアは、各配列が2つの減算に従ってソートされ、最初のn人が都市Aに飛んで、残りが都市Bに飛ぶというものです。

コード

class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        res=0
        costs.sort(key=lambda x:x[0]-x[1])
        n=len(costs)
        for i in range(n):
            if(i<n//2):
                res+=costs[i][0]
            else:
                res+=costs[i][1]
        return res

参照

2か所のスケジューリング

おすすめ

転載: blog.csdn.net/w5688414/article/details/115261241
おすすめ