洛谷p1094纪念品分组-贪心算法

本文介绍了一种优化纪念品配对的算法,旨在通过将大小纪念品配对以减少组数,实现资源的有效利用。算法首先对纪念品按大小排序,然后从两端开始尝试配对,确保每对纪念品的总重量不超过给定限制,以此达到最小化组数的目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.luogu.com.cn/problem/P1094
一组最多两件纪念品,那么一般小的纪念品都能凑成一对满足要求,但是大的纪念品就只能单独作为一组了,这无疑会增加组数,所以尽量为大的纪念品找小的纪念品凑成一对,这样最终一定会得到最优解

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;
#define MAX 30005

int arr[MAX];
int t[MAX];



int main() {
#ifdef ONLINE_JUDGE
#else
	freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
	int n, w, num = 1, sum = 0;
	cin >> w >> n; 
	for (int i = 0; i < n; i++)cin >> arr[i];
	sort(arr, arr + n);
	int l = 0, r = n - 1;
	while (l <= r) {
		if (arr[l] + arr[r] <= w)
			l++, r--, sum++;
		else
			r--, sum++;
	}
	cout << sum << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值