zoukankan      html  css  js  c++  java
  • 1029. 两地调度

    1029. 两地调度

    公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0],飞往 B 市的费用为 costs[i][1]。

    返回将每个人都飞到某座城市的最低费用,要求每个城市都有 N 人抵达。

    示例:

    输入:[[10,20],[30,200],[400,50],[30,20]]
    输出:110
    解释:
    第一个人去 A 市,费用为 10。
    第二个人去 A 市,费用为 30。
    第三个人去 B 市,费用为 50。
    第四个人去 B 市,费用为 20。

    最低总费用为 10 + 30 + 50 + 20 = 110,每个城市都有一半的人在面试。
     

    提示:

    1 <= costs.length <= 100
    costs.length 为偶数
    1 <= costs[i][0], costs[i][1] <= 1000

     1 扩展:如果有去多个城市的,那么如何解决,dp;
     2 
     3 思路:将这 2N 个人全都安排飞往 B 市,再选出 N 个人改变它们的行程,
     4 让他们飞往 A 市。如果选择改变一个人的行程,那么公司将会额外付出 price_A - price_B 的费用,
     5 这个费用可正可负。
     6 最优的方案是,选出 price_A - price_B 最小的 个人,让他们飞往 A 市,其余人飞往 B 市。
     7 
     8 排序方式
     9 sort(costs.begin(),costs.end(),[](vector<int> &a, vector<int> &b) {return a[0]-a[1] < b[0]-b[1];});
    10 sort(costs.begin(), costs.end(),[&](const vector<int> a1, const vector<int> b1){  return ((a1[1] - a1[0]) < (b1[1] - b1[0])); });
    11 
    12 把二维vector按costs[i][0]-costs[i][1]递增排序 一个人去A城市的价格减去他去B城市的价格越小,最好为负值,说明他去A城市越划算。
     1 class Solution {
     2 public:
     3     static bool cmp(vector<int>&x,vector<int>& y){
     4         return x[0]-x[1]<y[0]-y[1];
     5     }
     6     int twoCitySchedCost(vector<vector<int>>& costs) {
     7         /*思路:
     8             将数组按照去第一个城市-去第二个城市的 价格从小到大排序,
     9             [[184,139],[259,770],[448,54],[577,469],[840,118],[926,667]]
    10             1859           
    11         */
    12         sort(costs.begin(),costs.end(),cmp);
    13         int sum=0;
    14         for(int i=0;i<costs.size();i++){
    15             if(i<costs.size()/2)   sum+=costs[i][0];//前一半去A
    16             else sum+=costs[i][1];//后一半去B
    17         }
    18         return sum;
    19     }
    20 };
  • 相关阅读:
    (转)DMA(Direct Memory Access)
    linux根文件系统的挂载过程详解
    Linux根文件系统的挂载过程详解
    1byte、1KB、4KB,1MB、1GB用16进制表示的范围。任意地址范围求字节数
    Hi3531a海思logo加载的实现流程
    u-boot中添加mtdparts支持以及Linux的分区设置
    在uboot里面添加环境变量使用run来执行
    (转) 嵌入式 Linux 利用 udev 实现自动检测挂载U盘
    Shell之变量
    Shell之哈希表
  • 原文地址:https://www.cnblogs.com/NirobertEinteson/p/12002237.html
Copyright © 2011-2022 走看看