2024-02-08(贪心:排序不等式、绝对值不等式、推公式)

文章介绍了使用Java编写的三个问题,涉及排序算法(如快速排序)、绝对值不等式的解决方案以及利用Comparable接口实现的结构体在计算耍杂技牛的最大危险系数的应用。
摘要由CSDN通过智能技术生成

1.排序不等式

913. 排队打水 - AcWing题库

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = 100010;
        long res = 0;
        int[] t = new int[N];
        int n = sc.nextInt();
        for(int i = 0; i < n; i ++){
            t[i] = sc.nextInt();
        }
        Arrays.sort(t, 0, n);//排序
        for(int i = 0; i < n; i ++){
            res += t[i] * (n - 1 - i);//公式
        }
        System.out.print(res);
    }
}

2.绝对值不等式

104. 货仓选址 - AcWing题库

绝对值不等式

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int N = 100010;
        int[] a = new int[N];
        for(int i = 0; i < n; i ++){
            a[i] = sc.nextInt();
        }
        int res = 0;
        Arrays.sort(a, 0, n);
        for(int i = 0; i < n; i ++){
            res += Math.abs(a[i] - a[n / 2]);//找出中位点,记得要转换成绝对值
        }
        System.out.print(res);
    }
}

3.推公式

125. 耍杂技的牛 - AcWing题库

按照wi+si的顺序从小到大排,最大危险系数一定是最小的。 

import java.util.*;

class PII implements Comparable<PII>{//结构体
    int x, y;
    public PII(int x, int y){
        this.x = x;
        this.y = y;
    }
    public int compareTo(PII o){
        return Integer.compare(x, o.x);
    }
}

public class Main{
    static int w, s;
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = 50010;
        PII[] c = new PII[N];//用来存w+s
        int n = sc.nextInt();
        for(int i = 0; i < n; i ++){
            w = sc.nextInt();
            s = sc.nextInt();
            c[i] = new PII(w + s, w);
        }
        int res = -0x3f3f3f3f;
        Arrays.sort(c, 0, n);
        
        int sum = 0;
        for(int i = 0; i < n; i ++){
            w = c[i].y;
            s = c[i].x - w;
            res = Math.max(res, sum - s);
            sum += w;//记得加上前面牛牛的体重
        }
        System.out.print(res);
    }
}

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值