[题解]洛谷P1094——纪念品分组

原题链接: https://www.luogu.org/problem/P1094

题目简述:

NN件纪念品,每个纪念品都有特定的价格,要求将他们分组,每组纪念品之和不得超过MM,并且每组最多只能包含2件纪念品,请找出所有分组方案中最少的一个,并输出。

思路及代码:

读入后从小到大排序。
定义指针i j,并且i = 0,j = n-1,每次将a[i] ,a[j]相加,如果结果<m,就将他们分一组,否则让较大数单独一组,较小数继续寻找其他大数分组。

代码:

#include <bits/stdc++.h>
using namespace std;
int main() {
	int a[1101011];
	int i,j;
	int n,w;
	cin>>w>>n;
	for(int i = 0;i<n;++i) {
		cin>>a[i];
	}
	sort(a,a+n);
	i = 0;
	j = n-1;
	int ans = 0;
	i = 0;j = n-1;
	while(i<=j) {
		if(a[i]+a[j]<=w) {
			ans++;
			i++;
			j--;
			continue;
		} else {
			ans++;
			j--;
			continue;
		}
	}
	cout<<ans<<endl;
}

原文地址:https://www.cnblogs.com/littlefrog/p/11939496.html