ABC 245 | E - Wrapping Chocolate
题目描述
给定个矩形巧克力,第块宽为,长为;
给定个盒子,第个盒子宽为,长为;
每个盒子只能放一块巧克力,且只有当满足且,巧克力才能放入盒子;
问能否将所有巧克力都放入盒子中?
数据范围
解题思路
首先按照以下原则降序排序:
- 首先按照宽进行降序排序
- 若宽相等,按照长进行降序排序
- 若长与宽均相等,先排盒子,后排巧克力
代码如下:
struct Object{
int w, l, t;
bool operator < (const Object &p)const
{
if(w == p.w && l == p.l) return t > p.t;
if(w == p.w) return l > p.l;
return w > p.w;
}
} a[N];
排序后从左到右进行遍历:
- 若为盒子,则将长加入
multiset
- 若为巧克力,则在
multiset
中查找巧克力长的数字,若有,则继续查找;若无,则输出No
代码如下:
for(int i = 0; i < n + m; i ++){
if(a[i].t == 1) ss.insert(a[i].l);
else if(a[i].t == 0){
auto x = ss.lower_bound(a[i].l); //返回的是指向该位置的迭代器
if(x == ss.end()){ //可以直接比较,不打*
puts("No");
return 0;
}
else ss.erase(x); //删除对应地址的一个元素
}
}
puts("Yes");
该题要求我们找出一个合理的排序顺序,思维难点在于将巧克力与盒子混合排序,然后用multiset
在时间复杂度内得到答案。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
using namespace std;
const int N = 4e5 + 10;
int n, m;
multiset<int> ss;
struct Object{
int w, l, t;
bool operator < (const Object &p)const
{
if(w == p.w && l == p.l) return t > p.t;
if(w == p.w) return l > p.l;
return w > p.w;
}
} a[N];
int main()
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++) scanf("%d", &a[i].w), a[i].t = 0;
for(int i = 0; i < n; i ++) scanf("%d", &a[i].l);
for(int i = 0; i < m; i ++) scanf("%d", &a[i + n].w), a[i + n].t = 1;
for(int i = 0; i < m; i ++) scanf("%d", &a[i + n].l);
sort(a, a + n + m);
for(int i = 0; i < n + m; i ++){
if(a[i].t == 1) ss.insert(a[i].l);
else if(a[i].t == 0){
auto x = ss.lower_bound(a[i].l);
if(x == ss.end()){
puts("No");
return 0;
}
else ss.erase(x);
}
}
puts("Yes");
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库