import java.util.Scanner;
import java.util.Stack;
基本输入输出类
public class WaterPouring2012_10 {
publicstatic int A,B,C;//三个杯子的容量
publicstatic Stack<Integer[]> road=new Stack<Integer[]>();//记录倒水步骤
publicstatic boolean[][][] vis;状态标记
publicstatic int num=0;//记录解的数量
publicstatic int aim;//目标水量
publicstatic void main(String[] args) {
Scannersc=new Scanner(System.in);
A=sc.nextInt();
B=sc.nextInt();
C=sc.nextInt();
输入了三个数为瓶子的容量
vis=newboolean[2*A][2*A][2*A];
for(inti=0;i<A*2;i++)
for(intj=0;j<A*2;j++)
for(intk=0;k<A*2;k++)
vis[i][j][k]=false;
vis为标记数组这里全部置为假
intAstart=sc.nextInt();
intBstart=sc.nextInt();
intCstart=sc.nextInt();
输入目标容量
aim=sc.nextInt();
输入开始容量
road.push(newInteger[]{Astart,Bstart,Cstart});
将开始容量压栈
//vis[A][0][0]=true;
//PrintRoad();
Pouring(Astart,Bstart,Cstart);
执行功能程序
if(num==0)
{
System.out.println("不可能");
}
所得到的解不存在
}
publicstatic void Pouring(int x,int y,int z)
{
//System.out.println(x+""+y+" "+z+"qqq"+road.size());
if(x==aim||y==aim||z==aim)
{
num++;
System.out.println("num:"+num);
PrintRoad();
}
找到目标解我们就停止
一共之分六中情况我们这里来稍微讨论一下我们所说的这六种情况的条件
1 x>0 x+y<=B
2x>0&&y<b&&(x+y)>=b
我们可以看到我们是把自然条件放到了前面
最后加一个限制条件
elseif(x<=A&&y<=B&&z<=C&&!vis[x][y][z])//如果没访问过
{
vis[x][y][z]=true;//该节点的所有子结点全部被访问
//A->BA倒空
if((B-y)>=x&&x>0)
{
//System.out.print("A->BA倒空");
road.push(newInteger[]{0, x+y, z});
Pouring(0,x+y, z);
road.pop();
}
//A->BB倒满
if(y<B&&x>0&&(x+y)>=B)
{
//System.out.print("A->BB倒满");
road.push(newInteger[]{x+y-B, B, z});
Pouring(x+y-B,B, z);
road.pop();
}
//A->CA倒空
if((C-z)>=x&&x>0)
{
//System.out.print("A->CA倒空");
road.push(newInteger[]{0,y,x+z});
Pouring(0,y,x+z);
road.pop();
}
//A->CC倒满
if(z<C&&x>0&&(x+z)>=C)
{
//System.out.print("A->CC倒满");
road.push(newInteger[]{x+z-C,y,C});
Pouring(x+z-C,y,C);
road.pop();
}
//B->AB倒空
if((A-x)>=y&&y>0)
{
//System.out.print("B->AB倒空");
road.push(newInteger[]{x+y,0,z});
Pouring(x+y,0,z);
road.pop();
}
//B->AA倒满
if(x<A&&y>0&&(y+x)>=A)
{
//System.out.print("B->AA倒满");
road.push(newInteger[]{A,x+y-A,z});
Pouring(A,x+y-A,z);
road.pop();
}
//B->CB倒空
if((C-z)>y&&y>0)
{
//System.out.print("B->CB倒空");
road.push(newInteger[]{x,0,y+z});
Pouring(x,0,y+z);
road.pop();
}
//B->CC倒满
if(z<C&&y>0&&(y+z)>=C)
{
//System.out.print("B->CC倒满");
road.push(newInteger[]{x,y+z-C,C});
Pouring(x,y+z-C,C);
road.pop();
}
//C->AC倒空
if((A-x)>z&&z>0)
{
//System.out.print("C->AC倒空");
road.push(newInteger[]{x+z,y,0});
Pouring(x+z,y,0);
road.pop();
}
//C->AA倒满
if(x<A&&z>0&&(x+z)>=A)
{
//System.out.print("C->AA倒满");
road.push(newInteger[]{A,y,x+z-A});
Pouring(A,y,x+z-A);
road.pop();
}
//C->BC倒空
if((B-y)>z&&z>0)
{
//System.out.print("C->BC倒空");
road.push(newInteger[]{x,y+z,0});
Pouring(x,y+z,0);
road.pop();
}
//C->BB倒满
if(y<B&&z>0&&(y+z>=B))
{
//System.out.print("C->BB倒满");
road.push(newInteger[]{x,B,y+z-B});
Pouring(x,B,y+z-B);
road.pop();
}
}
}
publicstatic void PrintRoad()
{
for(inti=0;i<road.size();i++)
{
Integer[]tmp=road.get(i);
System.out.println("("+tmp[0]+","+tmp[1]+","+tmp[2]+")");
}
//road.push(newInteger[]{A,0,0});
}
}
输出模块