首页 > 其他 > 详细

1029. 两地调度

时间:2019-12-07 17:14:13      阅读:87      评论:0      收藏:0      [点我收藏+]

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 };

 

1029. 两地调度

原文:https://www.cnblogs.com/NirobertEinteson/p/12002237.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!