这题用bfs,bool数组判断是否走过(或者说判断是否存在过两个杯子的水量相同的情况),string stack 存步骤,(其实存步骤就算剪枝了),依次六个情况写入,这题就结束啦
import java.util.ArrayDeque;
import java.util.Scanner;
public class Main
{
static int leftwater, rightwater;
static boolean bool[][];
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
for (int t = 0;t < a; t++) {
int x, y, z;
x = sc.nextInt();
y = sc.nextInt();
z = sc.nextInt();
bool = new boolean[1005][1005];//判断是否存在过leftwater、rightwater 相同情况
leftwater = x;
rightwater = y;
ArrayDeque<node> que = new ArrayDeque<>();
que.add(new node(0, 0, 0, ""));
while (!que.isEmpty()) {
node ok = que.poll();
if (ok.right == z) {
System.out.print(ok.times);
for (int i = 0; i < ok.stack.length(); i++) {
System.out.print(" " + ok.stack.charAt(i));
}
System.out.println();
break;
}
if (bool[ok.left][ok.right])
continue;
bool[ok.left][ok.right] = true;
int left = ok.left;
int right = ok.right;
int times = ok.times;
String stack = ok.stack;
times += 1;
que.add(new node(leftwater, right, times, stack + "1"));
que.add(new node(left, rightwater, times, stack + "2"));
que.add(new node(0, right, times, stack + "3"));
que.add(new node(left, 0, times, stack + "4"));
if (right + left > leftwater) {
que.add(new node(leftwater, right - (leftwater - left), times, stack + "5"));
} else {
que.add(new node(left + right, 0, times, stack + "5"));
}
if (right + left > rightwater) {
que.add(new node(left - (rightwater - right), rightwater, times, stack + "6"));
} else {
que.add(new node(0, left + right, times, stack + "6"));
}
}
}
}
static void dp()
{
}
static class node
{
int left, right, times;
String stack;
public node(int left, int right, int times, String stack)
{
this.left = left;
this.right = right;
this.times = times;
this.stack = stack;
}
}
}