问:一群人过河,船最大承受maxwt,且一次最多装两个人,现在有people[].length个人,及对应体重people[i],求船的运输情况。
分析:前提是people数组有序。每次选最重的人与最轻的人一组坐船,若超重就只坐最重的船客。换下一组人,即倒数第二个人......最终送完所有人
1 | 2 | 3 | 4 | 5 |
只要left<=right就可以分组(最重最轻)且分完left++ right--,或者只是right--(只送最重那一个人),但是当left=right时说明只剩下一个人了,只能一个人坐一艘船。
public class greed {
public static void main(String[] args) {
// TODO Auto-generated method stub
int maxwt=6;//最大承重量
int people[]= {1,2,3,4,5};//乘客以及对应的重量情况
int count=0;//船的数量
int right=people.length-1;//右指针 最重的人
int left=0;//左指针 最轻的人
while(left<=right)
{
if(people[left]+people[right]<=maxwt)//最重和最轻的人都能上去
{
if(left==right)//只有一个人了,最之间剩余了一个人的特殊情况
{
count++;
System.out.println("第"+count+"只船上的乘客情况:"+people[left]);
left++;//无所谓,也可以是right++只要是让left!=right即可
}
else
{
count++;
System.out.println("第"+count+"只船上的乘客情况:"+people[left]+","+people[right]);
left++;
right--;
}
}
else {//只能拉最重的人
count++;
System.out.println("第"+count+"只船上的乘客情况:"+people[right]);
right--;
}
}
System.out.println("共花掉"+count+"艘船");
}
}