import java.util.List;
import java.util.ArrayList;
import java.math.BigDecimal;
/*-作者:volcano_hosan
*-----------蚂蚁爬杆
*有一根300厘米的细木杆,在第30厘米、80厘米、110厘米、160厘米、250厘米这五个位置上各有一只蚂蚁。
*木杆很细,不能同时通过两只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。
*当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝相反方向走。假设蚂蚁们每秒钟可以走5厘米的距离。
*请编写一个程序,计算各种可能情形下所有蚂蚁都离开木杆的最小时间和最大时间
*-------分析:两只蚂蚁碰头之后,因为是相同的个体,速度一样,只是不作停留掉头回走,可以认为两只蚂蚁的行进方向没有改变一直朝一个方向前进
*/
public class Ant{
private BigDecimal totalLength;
private BigDecimal speed;
private List positions;
private BigDecimal maxTime;
private BigDecimal minTime;
Ant(){
totalLength = new BigDecimal("300");
speed = new BigDecimal("5");
positions = new ArrayList();
positions.add(new BigDecimal("30"));
positions.add(new BigDecimal("80"));
positions.add(new BigDecimal("110"));
positions.add(new BigDecimal("160"));
positions.add(new BigDecimal("250"));
setMinTime();
setMaxTime();
}
private void setMaxTime(){
BigDecimal maxNearSidePosition = new BigDecimal("0");
for(BigDecimal position:positions){
maxNearSidePosition = maxNearSidePosition.intValue() > position.intValue() ? maxNearSidePosition : position;
}
maxTime = maxNearSidePosition.divide(speed);
}
public BigDecimal getMaxTime(){
return maxTime;
}
private void setMinTime(){
BigDecimal halfLength = totalLength.divide(new BigDecimal("2"));
BigDecimal minNearHalfPositionLength = halfLength;
for(BigDecimal position:positions){
BigDecimal nearHalfPositionLength = position.subtract(halfLength).abs();
minNearHalfPositionLength = minNearHalfPositionLength.intValue() < nearHalfPositionLength.intValue() ? minNearHalfPositionLength : nearHalfPositionLength;
}
BigDecimal anotherHalfLength = halfLength.subtract(minNearHalfPositionLength);
minTime = anotherHalfLength.divide(speed);
}
public BigDecimal getMinTime(){
return minTime;
}
public static void main(String []args){ Ant ant = new Ant(); System.out.println("最大时间:" + ant.getMaxTime()); System.out.println("最大时间:" + ant.getMinTime()); } }