题目描述
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.
Note:
1 <= costs.length <= 100
- It is guaranteed that
costs.length
is even. 1 <= costs[i][0], costs[i][1] <= 1000
题意:公司计划面试2N
人。第 i
人飞往 A市的费用为costs[i][0]
,飞往 B 市的费用为 costs[i][1]
。返回将每个人都飞到某座城市的最低费用,要求每个城市都有N
人抵达。
算法1
(排序+贪心) $O(n^logn)$
题解:贪心的做法。我们把每个人按照costs[i][0] - costs[i][1]
排序,这样排在前N
个位置的人就是去A的花费比去B的花费最小的N个人,我们就让这N个人去A市就是一个最优解。
证明如下:假设排好序前N
个人和后N
个人中任取两个人X,Y
,我们可以得到X[0] - X[1] < Y[0] - Y[1]
我们尝试将X,Y
交换,如果原来的总花费是Sum
,那么新的总花费就是Sum - X[0] + X[1] - Y[1] + Y[0] = Sum + (Y[0] - Y[1]) - (X[0] - Y[1]) > Sum
。所以不管怎么交换都无法得到最优解。
int twoCitySchedCost(vector<vector<int>>& costs) {
int n = costs.size(),res = 0;
sort(costs.begin(),costs.end(),[](const vector<int> &a,const vector<int> &b)
{
return (a[0] - a[1]) < (b[0] - b[1]);
});
for(int i = n / 2 - 1 ; i >= 0 ; i --)
res += costs[i][0];
for(int i = n / 2 ; i < n ; i ++)
res += costs[i][1];
return res;
}