zoukankan      html  css  js  c++  java
  • LeetCode1029 两地调度(贪心+java自定义排序回顾)

    题目:

    公司计划面试 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

    思路:

    贪心。首先让所有的人都去城市B,这时的所有人总的花费为sumB。因为是AB两个城市都要有人,所以要将一半的人调到城市A去,那这一半的人调动之后,

    总的花费用(sumB+被调动人员AB两个城市之间花费的差价)。现在来分析一下,这被调动的一半人是怎么确定的:

    sumB是固定不变的了,那就通过这个差价来做文章了,因为这个差价是costA-costB得来的,所以要使总的花费最小,就要让差价最小的那一半人调到城市A

    去。

    import java.util.*;
    import java.math.*;
    
    class Solution {
        public int twoCitySchedCost(int[][] costs) {
            int sum = 0,n = costs.length/2;
            Arrays.sort(costs, new Comparator<int[]>() {
                @Override
                public int compare(int[] o1, int[] o2) {
                    return (o1[0]-o1[1])-(o2[0]-o2[1]);
                }
            });
            //System.out.println("length: "+costs.length);
            for(int i=0; i<costs.length; i++){
                //System.out.println(costs[i][0]+","+costs[i][1]);
                sum += costs[i][1];
            }
            for(int i=0; i<n; i++){
                sum += costs[i][0]-costs[i][1];
            }
            return sum;
        }
    }
    
    public class Main {
        public static void main(String[] args){
            Scanner scanner = new Scanner(System.in);
            int n = scanner.nextInt();
            int[][] array = new int[4][2];
            for(int i=0; i<n; i++){
                array[i][0] = scanner.nextInt();
                array[i][1] = scanner.nextInt();
            }
            Solution solution = new Solution();
            System.out.println(solution.twoCitySchedCost(array));
        }
    }

    参考博友博客:

    https://blog.csdn.net/qq_41550842/article/details/96606437

    回顾了java中自定义排序的方法。

  • 相关阅读:
    UVA 11925 Generating Permutations 生成排列 (序列)
    UVA 1611 Crane 起重机 (子问题)
    UVA 11572 Unique snowflakes (滑窗)
    UVA 177 PaperFolding 折纸痕 (分形,递归)
    UVA 11491 Erasing and Winning 奖品的价值 (贪心)
    UVA1610 PartyGame 聚会游戏(细节题)
    UVA 1149 Bin Packing 装箱(贪心)
    topcpder SRM 664 div2 A,B,C BearCheats , BearPlays equalPiles , BearSorts (映射)
    UVA 1442 Cave 洞穴 (贪心+扫描)
    UVA 1609 Foul Play 不公平竞赛 (构(luan)造(gao)+递归)
  • 原文地址:https://www.cnblogs.com/sykline/p/12210667.html
Copyright © 2011-2022 走看看