Skip to content

Commit 3cb46bf

Browse files
Two City Scheduling
1 parent 9cfc475 commit 3cb46bf

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

3.cpp

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
3+
Two City Scheduling
4+
-------------------
5+
6+
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].
7+
8+
Return the minimum cost to fly every person to a city such that exactly N people arrive in each city.
9+
10+
11+
12+
Example 1:
13+
14+
Input: [[10,20],[30,200],[400,50],[30,20]]
15+
Output: 110
16+
Explanation:
17+
The first person goes to city A for a cost of 10.
18+
The second person goes to city A for a cost of 30.
19+
The third person goes to city B for a cost of 50.
20+
The fourth person goes to city B for a cost of 20.
21+
22+
The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
23+
24+
25+
Note:
26+
27+
1 <= costs.length <= 100
28+
It is guaranteed that costs.length is even.
29+
1 <= costs[i][0], costs[i][1] <= 1000
30+
*/
31+
32+
auto cmp = [](const vector<int>& lhs, const vector<int>& rhs) {
33+
return lhs[0] - lhs[1] < rhs[0] - rhs[1];
34+
};
35+
36+
class Solution {
37+
public:
38+
39+
int twoCitySchedCost(vector<vector<int>>& costs) {
40+
long long sum = 0;
41+
sort(costs.begin(), costs.end(), cmp);
42+
int n = costs.size()/2;
43+
for(int i=0; i<2*n; i++) {
44+
if(i < n) {
45+
sum += costs[i][0];
46+
} else {
47+
sum += costs[i][1];
48+
}
49+
}
50+
return sum;
51+
}
52+
};

0 commit comments

Comments
 (0)