【noip模拟】太空电梯 贪心

题目大意

人数n,电梯载重k,电梯限制人数2,给出每个人的体重v,求按照怎样的顺序排队电梯运送的次数越多。

题解

排序后,每次都先选择最小的,然后看最大的上来是否超出载重,

  • 若超出,则这两个对答案贡献2,

  • 若不超出,则再添加一个次小的(不浪费最大的).

code

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

const int N = 1e5 + 5;
int n, a[N], ans, k;

int main(){
	scanf("%d%d", &n, &k);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	sort(a + 1, a + n + 1);
	int head = 1, tail = n;
	while(head <= tail){
		if(head == tail){
			ans++;
			break;
		}
		else if(a[head] + a[tail] <= k){
			head += 2;
			ans++;
		}
		else{
			ans += 2;
			head++, tail--;
		}
		// cout<<ans<<endl;
	}
	printf("%d", ans);
	return 0;
}
原文地址:https://www.cnblogs.com/CzYoL/p/7450019.html