【算法基础:贪心】6. 贪心

文章目录

  • 区间问题
    • [905. 区间选点(排序 + 贪心)](#905. 区间选点(排序 + 贪心))
    • [908. 最大不相交区间数量(排序 + 贪心)](#908. 最大不相交区间数量(排序 + 贪心))
    • [906. 区间分组(排序 + 优先队列 + 贪心)⭐](#906. 区间分组(排序 + 优先队列 + 贪心)⭐)
    • [907. 区间覆盖(排序 + 贪心)](#907. 区间覆盖(排序 + 贪心))
  • Huffman树
    • [148. 合并果子(优先队列 + 贪心)](#148. 合并果子(优先队列 + 贪心))
  • 排序不等式
    • [913. 排队打水](#913. 排队打水)
  • 绝对值不等式
    • [104. 货仓选址(选中点位置)](#104. 货仓选址(选中点位置))
  • 推公式
    • [125. 耍杂技的牛⭐⭐⭐](#125. 耍杂技的牛⭐⭐⭐)

区间问题

对于区间问题,通常需要先排序,(一般情况下都是左端点排序)。

相关链接:【算法】区间合并类题目总结

905. 区间选点(排序 + 贪心)

https://www.acwing.com/activity/content/problem/content/1111/

解法可见:【算法】区间合并类题目总结 的问题 ------ 452. 用最少数量的箭引爆气球

可以左边界排序 或 右边界排序。

java 复制代码
import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] r = new int[n][2];
        for (int i = 0; i < n; ++i) {
            r[i][0] = sc.nextInt();
            r[i][1] = sc.nextInt();
        }
        // 按起点升序排序
        Arrays.sort(r, (a, b) -> a[0] - b[0]);
        
        int ans = 0, last = Integer.MIN_VALUE;
        for (int[] cur: r) {
            if (cur[0] <= last) last = Math.min(last, cur[1]);
            else {
                ++ans;
                last = cur[1];
            }
        }
        System.out.println(ans);
    }
}

908. 最大不相交区间数量(排序 + 贪心)

https://www.acwing.com/activity/content/problem/content/1112/

java 复制代码
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int n = sin.nextInt();
        int[][] r = new int[n][2];
        for (int i = 0; i < n; ++i) {
            r[i][0] = sin.nextInt();
            r[i][1] = sin.nextInt();
        }
        Arrays.sort(r, (a, b) -> a[0] - b[0]);  // 左端点排序
        int ans = 0, last = Integer.MIN_VALUE;
        for (int[] x: r) {
            if (x[0] > last) {
                ++ans;
                last = x[1];
            } else {
                last = Math.min(last, x[1]);
            }
        }
        System.out.println(ans);
    }
}

906. 区间分组(排序 + 优先队列 + 贪心)⭐

https://www.acwing.com/activity/content/problem/content/1113/

贪心思路:

使用优先队列来维护所有组的结束端点位置,这样就可以快速找到当前结束位置最靠前的组。

最后优先队列中有多少元素就表示需要多少组。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));

        int n = sin.nextInt();
        int[][] r = new int[n][2];
        for (int i = 0; i < n; ++i) {
            r[i][0] = sin.nextInt();
            r[i][1] = sin.nextInt();
        }
        Arrays.sort(r, (a, b) -> a[0] - b[0]);  // 左端点排序

        // pq 里存储了各个组的结束位置(从小到大排列)
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int[] x: r) {
            if (!pq.isEmpty() && pq.peek() < x[0]) pq.poll();   // 如果可以加入当前存在的组
            pq.offer(x[1]);
        }
        System.out.println(pq.size());
    }
}

907. 区间覆盖(排序 + 贪心)

https://www.acwing.com/problem/content/description/909/

每次贪心地找出符合左端点 <= start 的区间中右端点最远的那个。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        int s = sin.nextInt(), t = sin.nextInt();
        int n = sin.nextInt();
        int[][] r = new int[n][2];
        for (int i = 0; i < n; ++i) {
            r[i][0] = sin.nextInt();
            r[i][1] = sin.nextInt();
        }
        // 左端点升序排序
        Arrays.sort(r, (a, b) -> a[0] - b[0]);

        int ans = 0, last = s - 1;
        for (int i = 0, j; i < n && last < t; ++i) {
            j = i;          // j 从 i 开始枚举
            // 找到左端点<= s的区间中,右端点最大的那个
            while (j < n && r[j][0] <= s) {
                last = Math.max(last, r[j][1]);
                ++j;
            }
            ++ans;
            s = last + 1;   // 更新当前需要的开始端点
            i = Math.max(i, j - 1);
        }
        System.out.println(last >= t? ans: -1);
    }
}

Huffman树

148. 合并果子(优先队列 + 贪心)

https://www.acwing.com/problem/content/150/

贪心得想,每次先合并体力耗费小的。(因为先合并的对答案的贡献次数多)。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        int n = sin.nextInt();
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < n; ++i) pq.offer(sin.nextInt());

        int ans = 0;
        while (pq.size() > 1) {
            int c = pq.poll() + pq.poll();
            pq.offer(c);
            ans += c;
        }
        System.out.println(ans);
    }
}

排序不等式

913. 排队打水

https://www.acwing.com/problem/content/description/915/

先让接的快的人接水。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        int n = sin.nextInt();
        long[] times = new long[n];
        for (int i = 0; i < n; ++i) times[i] = sin.nextInt();
        Arrays.sort(times);
        long ans = 0;
        for (int i = 0; i < n; ++i) {
            ans += times[i] * (n - i - 1);
        }
        System.out.println(ans);
    }
}

绝对值不等式

104. 货仓选址(选中点位置)

https://www.acwing.com/problem/content/106/

选择中点位置即可。

具体的操作是找中位数。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        int n = sin.nextInt();
        long[] a = new long[n];
        for (int i = 0; i < n; ++i) a[i] = sin.nextLong();
        Arrays.sort(a);
        long pos = a[n / 2], ans = 0;
        for (int i = 0; i < n; ++i) {
            ans += Math.abs(pos - a[i]);
        }
        System.out.println(ans);
    }
}

推公式

125. 耍杂技的牛⭐⭐⭐

https://www.acwing.com/problem/content/127/

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

如何证明?------ 反证法
看 i 和 i + 1 交换位置之后会发生什么。

java 复制代码
import java.io.BufferedInputStream;
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sin = new Scanner(new BufferedInputStream(System.in));
        int n = sin.nextInt();
        int[][] cows = new int[n][2];
        for (int i = 0; i < n; ++i) {
            int w = sin.nextInt(), s = sin.nextInt();
            cows[i][0] = w + s;
            cows[i][1] = w;
        }
        Arrays.sort(cows, (a, b) -> a[0] - b[0]);

        int ans = 0, sum = 0;
        for (int i = 0; i < n; ++i) {
            int s = cows[i][0] - cows[i][1], w = cows[i][1];
            ans = Math.max(ans, sum - s);
            sum += w;
        }
        System.out.println(ans);
    }
}
相关推荐
学海_无涯_苦作舟1 分钟前
RabbitMQ Java Client源码解析——FrameHandler
java·rabbitmq·java-rabbitmq
88号技师1 分钟前
2025年10月一区SCI-中心碰撞优化算法Centered Collision Optimizer-附Matlab免费代码
开发语言·算法·数学建模·matlab·优化算法
毕设源码-赖学姐2 分钟前
【开题答辩全过程】以 果树的生长信息管理系统为例,包含答辩的问题和答案
java·spring boot
CodeCraft Studio2 分钟前
国产化PDF处理控件Spire.PDF教程:在Java快速解析PDF文本、表格、图像和元数据
java·python·pdf·pdf解析·spire.pdf·元数据解析·java pdf解析
zore_c3 分钟前
【数据结构】堆——超详解!!!(包含堆的实现)
c语言·开发语言·数据结构·经验分享·笔记·算法·链表
CryptoRzz3 分钟前
墨西哥股票数据 API 对接实战指南(含实时行情与 IPO 功能)
java·后端·websocket·区块链
hgz07105 分钟前
Spring Boot自动配置
java·springboot
@淡 定6 分钟前
慢查询分析与优化
java
大学生资源网7 分钟前
基于springboot的南京特色美食小吃商城(源码+文档)
java·spring boot·后端·mysql·毕业设计·源码
月明长歌11 分钟前
【码道初阶】【LeetCode387】如何高效找到字符串中第一个不重复的字符?
java·开发语言·数据结构·算法·leetcode·哈希算法