IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 数据结构与算法 -> POJ-2782 Bin Packing 题解 【贪心】 -> 正文阅读

[数据结构与算法]POJ-2782 Bin Packing 题解 【贪心】

题目:
A set of n 1-dimensional items have to be packed in identical bins. All bins have exactly the same length l and each item i has length li<=l . We look for a minimal number of bins q such that
? each bin contains at most 2 items,
? each item is packed in one of the q bins,
? the sum of the lengths of the items packed in a bin does not exceed l .
You are requested, given the integer values n , l , l1 , …, ln , to compute the optimal number of bins q .

输入:
The first line of the input contains the number of items n (1<=n<=105). The second line contains one integer that corresponds to the bin length l<=10000. We then have n lines containing one integer value that represents the length of the items.

输出:
Your program has to write the minimal number of bins required to pack all items.

输入样例:
10
80
70
15
30
35
10
80
20
35
10
30

输出样例:
6

提示:
The sample instance and an optimal solution is shown in the figure below. Items are numbered from 1 to 10 according to the input order.
在这里插入图片描述

题意:
给你很多大小不一的物品,装到大小为L的盒子里,且每个盒子最多装两个物品,问最少需要多少个盒子

题解:
从小到大排序。
利用两个指针,小指针从小到大,大指针从大到小遍历,使用一个盒子,先取大那头物体装入,大指针左移,如果剩余空间足够再装个小的,则将小的装入,小指针右移,否则继续取盒子,重复到所有物体装完(指针相交错开)。

AC代码:

#include<iostream>
#include<cstdio>
#include<algorithm>
#define ll long long
using namespace std;
int n,m,ans;
int a[100005];
int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++){
		scanf("%d",&a[i]);
	} 
	sort(a,a+n);
	ans=0;
	for(int i=0,j=n-1;i<=j;){
		ans++;
		if(a[i]+a[j]>m){
			j--;
		}
		else{
			i++;
			j--;
		}
	}
	printf("%d\n",ans);
	return 0;
}
  数据结构与算法 最新文章
【力扣106】 从中序与后续遍历序列构造二叉
leetcode 322 零钱兑换
哈希的应用:海量数据处理
动态规划|最短Hamilton路径
华为机试_HJ41 称砝码【中等】【menset】【
【C与数据结构】——寒假提高每日练习Day1
基础算法——堆排序
2023王道数据结构线性表--单链表课后习题部
LeetCode 之 反转链表的一部分
【题解】lintcode必刷50题<有效的括号序列
上一篇文章      下一篇文章      查看所有文章
加:2021-10-02 15:06:48  更:2021-10-02 15:07:52 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/17 10:02:17-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码