韩信分油

/ 智力题java / 没有评论 / 384浏览

韩信是中国古代的一位名将,聪明过人。据说有一天,他骑马在路上走,看见路旁有两个人正在为分油发愁。了解后,知道两个人有可装10斤、7斤、3斤油的三只容器,10斤的大容器里装满了油,7斤、3斤的容器都是空的,现在要把这10斤油平均分,每人分5斤。两人都没有带秤,应该怎么分呢?

Java代码:

public class Test002 {

	public static void main(String[] args) {
		int a = 10;
		int a1 = 10;
		int b = 7;
		int b1 = 0;
		int c = 3;
		int c1 = 0;
		int targe = 5;
		fenyou(a, a1, b, b1, c, c1, targe);
	}
	public static void fenyou(int a,int a1,int b,int b1,int c,int c1,int targe){
		
		if(b1==0){
			int temp = b - b1;
			a1 = a1 - temp;
			b1 = b1 + temp;
			System.out.println("a向b倒油" + temp + ",当前a=" + a1 + ",b=" + b1 + ",c=" + c1);
		}
		if(c1<=c && b1>(c-c1)){
			int temp = c - c1;
			b1 = b1 - temp;
			c1 = c1 + temp;
			System.out.println("b向c倒油" + temp + ",当前a=" + a1 + ",b=" + b1 + ",c=" + c1);
		}else{
			int temp = b1;
			b1 = 0;
			c1 = c1 + temp;
			System.out.println("b向c倒油" + temp + ",当前a=" + a1 + ",b=" + b1 + ",c=" + c1);
		}
		if(c1==c){
			int temp = c1;
			c1 = 0;
			a1 = a1 + temp;
			System.out.println("c向a倒油" + temp + ",当前a=" + a1 + ",b=" + b1 + ",c=" + c1);
		}
		if(a1!=(a/2)&&b1!=(a/2)){
			fenyou(a, a1, b, b1, c, c1, targe);
		}
	}

}

运行结果:

a向b倒油7,当前a=3,b=7,c=0

b向c倒油3,当前a=3,b=4,c=3

c向a倒油3,当前a=6,b=4,c=0

b向c倒油3,当前a=6,b=1,c=3

c向a倒油3,当前a=9,b=1,c=0

b向c倒油1,当前a=9,b=0,c=1

a向b倒油7,当前a=2,b=7,c=1

b向c倒油2,当前a=2,b=5,c=3

c向a倒油3,当前a=5,b=5,c=0

点击这里给我发消息
嘿!有什么能帮到您的吗?