标签:
进行一次独木舟的旅行活动,独木舟可以在港口租到,并且之间没有区别。一条独木舟最多只能乘坐两个人,且乘客的总重量不能超过独木舟的最大承载量。我们要尽量减少这次活动中的花销,所以要找出可以安置所有旅客的最少的独木舟条数。现在请写一个程序,读入独木舟的最大承载量、旅客数目和每位旅客的重量。根据给出的规则,计算要安置所有旅客必须的最少的独木舟条数,并输出结果。
3 85 6 5 84 85 80 84 83 90 3 90 45 60 100 5 50 50 90 40 60
5 3 3
代码:
package acm71;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int group = input.nextInt();
for (int i = 0;i<group;i++) {
int weight = input.nextInt();
int number = input.nextInt();
int array[] = new int[number];
for (int j = 0;j<array.length;j++) {
array[j] = input.nextInt();
}
int people = solution(array,weight,number);
System.out.println(people);
}
}
private static int solution(int[] array,int weight,int number) {
//排序
Arrays.sort(array);
//1:首先判断里面
int result = 0;
int i = 0;
int j = number-1;
while (i <= j) {
if (array[i] + array[j] > weight) {
j--;
result++;
}else{
i++;
j--;
result++;
}
}
return result;
}
}
标签:
原文地址:http://www.cnblogs.com/airycode/p/5539503.html