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

news2024/9/25 1:22:53

文章目录

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

区间问题

对于区间问题,通常需要先排序,(一般情况下都是左端点排序)。
相关链接:【算法】区间合并类题目总结

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

https://www.acwing.com/activity/content/problem/content/1111/
在这里插入图片描述
解法可见:【算法】区间合并类题目总结 的问题 —— 452. 用最少数量的箭引爆气球

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

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/

在这里插入图片描述

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/

在这里插入图片描述

贪心思路:
在这里插入图片描述

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

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

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 的区间中右端点最远的那个。

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/

在这里插入图片描述

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

在这里插入图片描述

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/

在这里插入图片描述

先让接的快的人接水。

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/
在这里插入图片描述

选择中点位置即可。
具体的操作是找中位数。

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 交换位置之后会发生什么。

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);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/810301.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【LeetCode 75】第十四题(643)子数组最大平均数

题目: 示例: 分析: 给一个数组,问数组里长度为k的连续数组中的最大平均值是多少. 这题已经把意思说的很明白了,并且连子数组的长度都固定了,并且是连续的,这里可以直接使用固定长度的滑动窗口来计算. 用两个指针来在数组里划定一个长度为k的范围,然后计算指针范围内的平均数…

数组传参,指针传参

文章目录 一维数组传参二维数组传参一级指针传参二级指针传参 一维数组传参 二维数组传参 一级指针传参 二级指针传参

CentOS 8 上安装 Nginx

Nginx是一款高性能的开源Web服务器和反向代理服务器&#xff0c;以其轻量级和高效能而广受欢迎。在本教程中&#xff0c;我们将学习在 CentOS 8 操作系统上安装和配置 Nginx。 步骤 1&#xff1a;更新系统 在安装任何软件之前&#xff0c;让我们先更新系统的软件包列表和已安…

【树链剖分+MST】CF609E

Problem - E - Codeforces 题意&#xff1a; 思路&#xff1a; 先把全局的MST求出来&#xff0c;然后对于一条边&#xff0c;如果它本来就在MST中&#xff0c;说明代价就是MST的权值和&#xff0c;否则它加入MST中&#xff0c;此时MST形成了环&#xff0c;我们把环中最大的那…

深入探究Java面向对象的三大特征:封装、继承、多态

文章目录 1. 封装&#xff08;Encapsulation&#xff09;2. 继承&#xff08;Inheritance&#xff09;3. 多态&#xff08;Polymorphism&#xff09;结语 导语&#xff1a;Java是一门面向对象的编程语言&#xff0c;其核心思想是将现实世界中的事物抽象成对象&#xff0c;并通过…

Python(五十二)列表元素的判断及遍历

❤️ 专栏简介&#xff1a;本专栏记录了我个人从零开始学习Python编程的过程。在这个专栏中&#xff0c;我将分享我在学习Python的过程中的学习笔记、学习路线以及各个知识点。 ☀️ 专栏适用人群 &#xff1a;本专栏适用于希望学习Python编程的初学者和有一定编程基础的人。无…

自己整理的JAVA集合

概括&#xff1a; 数组&#xff0c;链表&#xff0c;散列表&#xff0c;二分查找树&#xff0c;红黑树是五种不同的数据结构&#xff0c;它们有各自的特点和用途。ArrayList&#xff0c;LinkedList&#xff0c;HashTable&#xff0c;LinkedHashMap&#xff0c;HashMap 是 Java…

Camera组件

Clear Flags&#xff1a; Skybox&#xff1a;天空盒 Solid Color&#xff1a;填充颜色&#xff0c;当有空白处时填充背景颜色 Depth Only&#xff1a;只渲染想要渲染的层级 Dont Clear&#xff1a;不清除上一帧所留下来的数据&#xff0c;可以做类似残影的效果 Culling Mas…

Unity Addressable

Unity重要目录 工程中的几个重要目录 Assets存放资源、代码、配置Library大部分的资源导入到Assets目录之后&#xff0c;会转化成Unity认可的文件&#xff0c;转化后的文件会存储在这个目录Logs日志文件Packages第三方插件ProjectSettings存放各种项目设定UserSettings用户偏好…

CentOS 8 错误: Error setting up base repository

配置ip、掩码、网关、DNS VMware网关可通过如下查看 打开网络连接 配置镜像的地址 vault.centos.org/8.5.2111/BaseOS/x86_64/os/

java 阿里云 发送短信功能实现

1. 注册短信平台(以阿里云为例) 常用短信服务平台&#xff1a;阿里云、华为云、腾讯云、京东、梦网、乐信等 2. 注册成功后&#xff0c;开通短信服务 3. 设置短信签名、短信模板、AccessKey AccessKey 是访问阿里云 API 的密钥&#xff0c;具有账户的完全权限&#xff0c;我们…

C语言实现三子棋游戏

test.c源文件 - 三子棋游戏测试 game.h头文件 - 三子棋游戏函数的声明 game.c源文件 - 三子棋游戏函数的实现 主函数源文件&#xff1a; #define _CRT_SECURE_NO_WARNINGS 1#include"game.h" //自己定义的用"" void menu() {printf("*************…

代码随想录算法训练营day43

文章目录 Day43 最后一块石头的重量II题目思路代码 目标和题目思路代码 一和零题目思路代码 Day43 最后一块石头的重量II 1049. 最后一块石头的重量 II - 力扣&#xff08;LeetCode&#xff09; 题目 有一堆石头&#xff0c;每块石头的重量都是正整数。 每一回合&#xff0…

2023-07-30 LeetCode每日一题(环形链表 II)

2023-07-30每日一题 一、题目编号 142. 环形链表 II二、题目链接 点击跳转到题目位置 三、题目描述 给定一个链表的头节点 head &#xff0c;返回链表开始入环的第一个节点。 如果链表无环&#xff0c;则返回 null。 如果链表中有某个节点&#xff0c;可以通过连续跟踪 n…

【探索C++中的顺序表】手动实现vector容器

&#x1f680;write in front&#x1f680; &#x1f4dc;所属专栏&#xff1a;初阶数据结构 &#x1f6f0;️博客主页&#xff1a;睿睿的博客主页 &#x1f6f0;️代码仓库&#xff1a;&#x1f389;VS2022_C语言仓库 &#x1f3a1;您的点赞、关注、收藏、评论&#xff0c;是对…

Fourier变换及其应用(Brad G. Osgood)——第2章——Fourier变换

第2章 Fourier变换 2.1 初识Fourier变换(A First Look at the Fourier Transform) 我们即将从Fourier级数过渡到Fourier变换。“过渡(transition)”是合适的词&#xff0c;因为我们选择了Fourier变换从周期函数到非周期函数的引出路径。 为了完成这一旅程&#xff0c;我们将把…

【优选算法题练习】day10

文章目录 一、137. 只出现一次的数字 II1.题目简介2.解题思路3.代码4.运行结果 二、剑指 Offer 53 - II. 0&#xff5e;n-1中缺失的数字1.题目简介2.解题思路3.代码4.运行结果 三、153. 寻找旋转排序数组中的最小值1.题目简介2.解题思路3.代码4.运行结果 总结 一、137. 只出现一…

登录报错 “msg“:“Request method ‘GET‘ not supported“,“code“:500

1. 登录失败 2. 排查原因, 把 PostMapping请求注释掉, 或改成GetMapping请求就不会报错 3. 找到SecurityConfig.java , 新增 .antMatchers("/**/**").permitAll() //匹配允许所有路径 4. 登录成功

【算法基础:动态规划】5.4 状态压缩DP

文章目录 例题列表291. 蒙德里安的梦想⭐⭐⭐⭐⭐91. 最短Hamilton路径⭐⭐⭐ 相关链接 例题列表 291. 蒙德里安的梦想⭐⭐⭐⭐⭐ https://www.acwing.com/problem/content/293/ 当横向方格摆放完成后&#xff0c;纵向方格的拜访方式就已经确定了。&#xff08;因为我们只要求…

井字棋(TicTacToe)

目录 三种游戏 习题 1. 传统设置 2. 中间的网格 三种游戏 “选15”、“井字棋”、“魔幻15”游戏本质上是同一个游戏。 function tictactoe(job) % TICTACTOE Pick15, TicTacToe, and Magic3. % % Pick15. Pick single digit numbers. Each digit can be chosen % on…