问题:
有一根27厘米的细长杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一个蚂蚁。木杆很细,不能同时通过两只蚂蚁。开始时,蚂蚁的头朝左韩式朝右是任意的,它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头是,它们会同时调头朝反方向走。假设蚂蚁们每秒可以走一厘米。编写程序,求所有蚂蚁都离开木杆的最短时间和最长时间。
解法:
虽然两个蚂蚁相遇后是调头往反方向走,但是,可以“看做”两个蚂蚁相遇后,擦肩而过。也就是说,可以认为蚂蚁的运动是独立的,是否碰头并不是重点。
程序:
import java.util.*;
/*
*@author 李洪岩
*@csdn Unixmale
*/
public class Demo47{
private int length;
{
this.length = 27;
}
public int getMax(int x,int y,int m,int n){
x = (x-0)>(length-x)?(x-0):(length-x);
y = (y-0)>(length-y)?(y-0):(length-y);
m = (m-0)>(length-m)?(m-0):(length-m);
n = (n-0)>(length-n)?(n-0):(length-n);
return x+y+m+n;
}
public int getMin(int x,int y,int m,int n){
x = (x-0)<(length-x)?(x-0):(length-x);
y = (y-0)<(length-y)?(y-0):(length-y);
m = (m-0)<(length-m)?(m-0):(length-m);
n = (n-0)<(length-n)?(n-0):(length-n);
return x+y+m+n;
}
public static void main(String[] args){
Demo47 demo = new Demo47();
int x;int y;int m;int n;
Scanner scan = new Scanner(System.in);
x = scan.nextInt();
y = scan.nextInt();
m = scan.nextInt();
n = scan.nextInt();
System.out.println(demo.getMax(x,y,m,n));
System.out.println(demo.getMin(x,y,m,n));
}
}