[LEETCODE June Challenge] 03 Two City Scheduling

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 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.

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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值