公司组织团建活动,到某漂流圣地漂流,现有如下情况:
员工各自体重不一,第 i 个人的体重为 people[i],每艘漂流船可以承载的最大重量为 limit。
每艘船最多可同时载两人,但条件是这些人的重量之和最多为 limit。
为节省开支,麻烦帮忙计算出载到每一个人所需的最小船只数(保证每个人都能被船载)。
输入描述:
第一行输入参与漂流的人员对应的体重数组, 第二行输入漂流船承载的最大重量
输出描述:
所需最小船只数
示例1
输入
1 2 3
输出
1
解题思路:
贪心。
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] strs = sc.nextLine().split(" ");
int[] nums = new int[strs.length];
for(int i=0; i<strs.length; i++)
nums[i] = Integer.valueOf(strs[i]);
int max = sc.nextInt();
Arrays.sort(nums);
int res = 0;
int l = 0, r = nums.length-1;
while(l < r){
if(nums[l] + nums[r] <= max){
l++;
r--;
}else
r--;
res++;
}
if(l == r)
res++;
System.out.print(res);
}
}
本文介绍了一种计算公司团建活动中,基于员工体重和船只承载限制,所需最小船只数量的方法。通过贪心算法,确保了成本的有效控制。
1496

被折叠的 条评论
为什么被折叠?



