人与马做的网站,东莞网页制作与网站设计,绍兴网站的优化,石家庄做网站公司文章目录1. 题目2. 贪心1. 题目
公司计划面试 2N 人。第 i 人飞往 A 市的费用为 costs[i][0]#xff0c;飞往 B 市的费用为 costs[i][1]。
返回将每个人都飞到某座城市的最低费用#xff0c;要求每个城市都有 N 人抵达。
示例#xff1a;
输入#xff1a;[[10,20],[30,2…
文章目录1. 题目2. 贪心1. 题目
公司计划面试 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来源力扣LeetCode 链接https://leetcode-cn.com/problems/two-city-scheduling 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。
2. 贪心
将数据按照 A-B 的花费差值排序小到大前半部分去A后半部分去B
A1−B1C1,A2−B2C2{ {A_1} - {B_1} {C_1}, {A_2} - {B_2} {C_2} }A1−B1C1,A2−B2C2
C1C2{ {C_1} {C_2} }C1C2
A1−B1A2−B2⇒A1B2A2B1{{A_1} - {B_1} {A_2} - {B_2} \Rightarrow {A_1} {B_2} {A_2} {B_1}} A1−B1A2−B2⇒A1B2A2B1
所以1去A2去B
class Solution {
public:int twoCitySchedCost(vectorvectorint costs) {int n costs.size();vectorpairint,int v(n);int i, money 0;for(i 0; i n; i){v[i].first costs[i][0]-costs[i][1];v[i].second i;}sort(v.begin(),v.end(),[](auto a, auto b){return a.first b.first;});for(i 0; i n/2; i)money costs[v[i].second][0];for(i n/2; i n; i)money costs[v[i].second][1];return money;}
};