Problem Description
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 iscosts[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.
Solution
Goal: minimize cost_A + cost_B, s.t. people_A = people_B = N
先看看Example分析一下。先看看每个人的cost_A - cost_B
。对于第一个人,选A会比选B节省10; 第二个人, 选A会比选B节省170; 第三个人, 选A会比选B多花费350; 第四个人, 选A会比选B多花费10. 我们要使总的cost最少,对于去A城市就是尽量优先选择节省的那一部分, 对于去B城市就是尽量选择多花费的那一部分。
按A-B从小到大排个序。由于一半的人去A城市一半去B,那么就前半部分的人去A城市,后半部分去B。終わった。
可以多拿几个例子写写看 都是一样的
上代码
class Solution {
static bool comp(vector<int>& a, vector<int>& b) {
return (a[0]-a[1])<(b[0]-b[1]);
}
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
int size = costs.size();
sort(costs.begin(), costs.end(), comp);
int res = 0;
for(int i=0; i<size; i++){
if (i<size/2) {
res += costs[i][0];
}
else {
res += costs[i][1];
}
}
return res;
}
};