P1432 倒水问题 LUOGU 洛谷 JAVA

这题用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;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值