1029.cpp (812B)
1 class Solution { 2 public: 3 int twoCitySchedCost(vector<vector<int>> &costs) { 4 sort(begin(costs), end(costs), 5 [](const auto &a, const auto &b) { return (a[0] - a[1]) < (b[0] - b[1]); }); 6 int n = costs.size() / 2, res = 0; 7 for (int i = 0; i < n; i++) 8 res += costs[i][0] + costs[i + n][1]; 9 return res; 10 } 11 }; 12 13 // Little optimization 14 class Solution { 15 public: 16 int twoCitySchedCost(vector<vector<int>> &costs) { 17 const int n = costs.size() / 2; 18 nth_element(begin(costs), begin(costs) + n, end(costs), 19 [](const auto &a, const auto &b) { return (a[0] - a[1]) < (b[0] - b[1]); }); 20 int res = 0; 21 for (int i = 0; i < n; i++) 22 res += costs[i][0] + costs[i + n][1]; 23 return res; 24 } 25 };