四十四、贪心——绝对值不等式、推公式

这里写目录标题

  • 一、绝对值不等式
    • 1、题目内容——货仓选址
    • 2、算法思路
      • (1)绝对值不等式
      • (2)算法思路
    • 3、题解
  • 二、推公式
    • 1、题目内容——耍杂技的牛
    • 2、算法思路
    • 3、题解

一、绝对值不等式

  • 贪心思想:
    • 中位数到一条数轴上的每个点的距离总和最小

1、题目内容——货仓选址

四十四、贪心——绝对值不等式、推公式_第1张图片

2、算法思路

(1)绝对值不等式

四十四、贪心——绝对值不等式、推公式_第2张图片

(2)算法思路

四十四、贪心——绝对值不等式、推公式_第3张图片

3、题解

import java.util.*;
import java.io.*;

public class Main{
    static int N = 100010;
    static int[] a = new int[N];
    
    
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
        String str1 = in.readLine();
        int n = Integer.parseInt(str1);
        
        String[] str2 = in.readLine().split(" ");
        
        for(int i = 0; i < n; i++){
            a[i] = Integer.parseInt(str2[i]);
        }
        
        Arrays.sort(a, 0, n);           // 排序是为了找出中位数
        
        long res = 0;
        
        for(int i = 0; i < n; i++){
            res += Math.abs(a[i] - a[n / 2]);       // 直接求和中位数之间的距离即为最小
        }
        
        
        System.out.println(res);
        
    }
}

二、推公式

  • 贪心思想:
    • 按照属性和进行排序,得到最优

1、题目内容——耍杂技的牛

四十四、贪心——绝对值不等式、推公式_第4张图片

2、算法思路

  • 排序方法:
    • 按照 wi + si 从小到大的顺序进行排序,值最大的,危险系数一定是最小的

3、题解

import java.util.*;
import java.io.*;

public class Main{
    
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        List<PIIs> list = new ArrayList<PIIs>();
        
        String str1 = in.readLine();
        int n = Integer.parseInt(str1);
        
        for(int i = 0; i < n; i++){
            String[] str2 = in.readLine().split(" ");
            int w = Integer.parseInt(str2[0]);
            int s = Integer.parseInt(str2[1]);
            list.add(new PIIs(w + s, w));           // 按照w+s从小到大排序,最大的危险系数一定是最小的
        }
        
        Collections.sort(list);
        
        int res = Integer.MIN_VALUE;
        int sumWeigt = 0;                           // 记录当前层上面所有牛已经有多重了,为了求解危险系数用的
        
        for(PIIs item:list){
            int w = item.getSecond();
            int s = item.getFirst() - w;
            
            res = Math.max(res, sumWeigt - s);      // 求解min(max(危险系数))
            sumWeigt += w;                          // 下一层的牛需要承担的重量
        }
        
        System.out.println(res);
    }
}



class PIIs implements Comparable<PIIs>{
    private int first;
    private int second;
    
    public PIIs(int first, int second){
        this.first = first;
        this.second = second;
    }
    
    public int getFirst(){
        return this.first;
    }
    
    public int getSecond(){
        return this.second;
    }
    
    public int compareTo(PIIs o){
        return Integer.compare(this.first, o.first);            // 按照w+s进行排序
    }
    
}

你可能感兴趣的:(数据结构与算法,java,开发语言,贪心算法,算法,数据结构)