算法学习日记--蚂蚁爬杆

问题:

         有一根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));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值