Leetcode 1029 Two City Scheduling (两个城市调度) (Greey, DP)
Leetcode 1029
题目描述
There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1].
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
例子
Example 1:
Input: [[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.
解题思路
方法一:(贪心算法)
按照cost[0]-cost[1]排序,前N个fly to A,后N个fly to B
Python
class Solution:
def twoCitySchedCost(self, costs):
N = len(costs)
dummy = []
for cost in costs:
dummy.append([cost, cost[0]-cost[1]])
dummy = sorted(dummy, key=(lambda x : x[1]))
ans = 0
for i in range(N):
ans += dummy[i][0][0] if i< N>>1 else dummy[i][0][1]
return ans
Java
class Solution {
public int twoCitySchedCost(int[][] costs){
Arrays.sort(costs, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
return (a[0]+b[1]) - (a[1]+b[0]);
}
});
int ans = 0;
for(int i=0; i<costs.length; ++i){
ans += i < costs.length>>1? costs[i][0]:costs[i][1];
}
return ans;
}
}
}
方法二:(动态规划)
Python
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
N = len(costs)>>1
dp = [[0 for _ in range(N+1)] for _ in range(N+1)]
for i in range(1,N+1):
dp[i][0] = dp[i-1][0]+costs[i-1][0]
for j in range(1,N+1):
dp[0][j] = dp[0][j-1]+costs[j-1][1]
for i in range(1,N+1):
for j in range(1,N+1):
dp[i][j] = min(dp[i-1][j]+costs[i+j-1][0], dp[i][j-1]+costs[i+j-1][1])
return dp[-1][-1]
Java
class Solution {
public int twoCitySchedCost(int[][] costs) {
int N = costs.length >> 1;
int[][] dp = new int[N + 1][N + 1];
for (int i = 1; i <= N; ++i) {
dp[i][0] = dp[i - 1][0] + costs[i - 1][0];
}
for (int j = 1; j <= N; ++j) {
dp[0][j] = dp[0][j - 1] + costs[j - 1][1];
}
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= N; ++j) {
dp[i][j] = Math.min(dp[i - 1][j] + costs[i + j - 1][0], dp[i][j - 1] + costs[i + j - 1][1]);
}
}
return dp[N][N];
}
}