Allowance POJ - 3040

题目链接

思路

我们每次先从大到小取,如果有刚好是加起来 \(C\) 的一些数据,那就直接拿来,否则就从小到大取,能取了就直接答案加 \(1\) ,如果最后加起来还不足 \(C\) 元,就说明没有答案了。

代码

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 30;
int n,m;
struct item {
	int v,s;
}a[N];
bool cmp (item x,item y) {
	return x.v > y.v;
}
int main () {
	cin >> n >> m;
	for (int i = 1;i <= n;i++) cin >> a[i].v >> a[i].s;
	sort (a + 1,a + 1 + n,cmp);  //从大到小排序
	int pos = 1;  //pos表示第一个小于C(即代码里的m)的下标
	for (;pos <= n;pos++) {
		if (a[pos].v < m) break;
	}
	int ans = 0;
	for (int i = 1;i < pos;i++) ans += a[i].s;    //pos表示第一个小于C(即代码里的m)的下标,所以要使用小于号
	while (true) {
		bool flag = false;
		int now = 0;
		for (int i = pos;i <= n;i++) {
			while (a[i].s && now + a[i].v <= m) {
				now += a[i].v;
				a[i].s--;
			}
		}  //这里其实可以直接判断,但不写判断也是可以的
		for (int i = n;i >= pos;i--) {
			while (a[i].s && now < m) {
				now += a[i].v;
				a[i].s--;
			}
		}
		if (now < m) break;  //不够就直接推出
		ans++;
	}
	cout << ans << endl;
	return 0;
}
posted @ 2022-09-02 19:21  incra  阅读(22)  评论(0)    收藏  举报