[アルゴリズム]LeetCode-Two City計画
LeetCode - Two City Scheduling
問題の説明
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
I/O例
Example 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.
Example 2:
Input: costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
Output: 1859
せいげんじょうけん
2 * n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000
Solution
[戦略]
1、2 n人とも都会Bに行った時の和.
2.(Aが選択されて増加した費用-Bが選択されずに減少した費用)がpriorityqueueを構成する.
3、総和最小を方向として、n人を変えてA市を選ぶ.import java.util.PriorityQueue;
class Solution {
public int twoCitySchedCost(int[][] costs) {
int minSumB = 0;
for (int i = 0; i < costs.length; i++) {
minSumB += costs[i][1];
}
PriorityQueue<Integer> abDiff = new PriorityQueue<>();
for (int i = 0; i < costs.length; i++) {
abDiff.add(costs[i][0] - costs[i][1]);
}
for (int i = 0; i < costs.length / 2; i++) {
minSumB += abDiff.poll();
}
return minSumB;
}
}
Reference
この問題について([アルゴリズム]LeetCode-Two City計画), 我々は、より多くの情報をここで見つけました
https://velog.io/@jerry92/알고리즘-LeetCode-Two-City-Scheduling
テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Return the minimum cost to fly every person to a city such that exactly n people arrive in each city.
2 * n == costs.length
2 <= costs.length <= 100
costs.length is even.
1 <= aCosti, bCosti <= 1000
import java.util.PriorityQueue;
class Solution {
public int twoCitySchedCost(int[][] costs) {
int minSumB = 0;
for (int i = 0; i < costs.length; i++) {
minSumB += costs[i][1];
}
PriorityQueue<Integer> abDiff = new PriorityQueue<>();
for (int i = 0; i < costs.length; i++) {
abDiff.add(costs[i][0] - costs[i][1]);
}
for (int i = 0; i < costs.length / 2; i++) {
minSumB += abDiff.poll();
}
return minSumB;
}
}
Reference
この問題について([アルゴリズム]LeetCode-Two City計画), 我々は、より多くの情報をここで見つけました https://velog.io/@jerry92/알고리즘-LeetCode-Two-City-Schedulingテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol