[Java] Mother‘s Milk

该程序采用Java编写,实现了一个深度优先搜索(DFS)算法,用于解决从A、B、C三个桶中转移牛奶,使得C桶达到特定容量的问题。程序首先读取输入数据,然后通过DFS遍历所有可能的转移方案,并使用HashSet存储已访问状态,避免重复。最终输出能够使C桶满的最小转移次数。
摘要由CSDN通过智能技术生成
/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: milk3
*/
import java.io.*;
import java.util.*;

public class milk3 {

	private int A;
	private int B;
	private int C;
	
	private void DFS(int a, int b, int c, boolean[] flag, Set<String> set) {
		if (set.contains(b + " " + c)) {
			return;
		}
		if (a == 0) {
			flag[c] = true;
		}
		set.add(b + " " + c);
		if (a != 0) {
			// a -> b
			if (b != B) {
				DFS(a - Math.min(B - b, a), b + Math.min(B - b, a), c, flag, set);
			}
			// a -> c
			if (c != C) {
				DFS(a - Math.min(C - c, a), b, c + Math.min(C - c, a), flag, set);
			}
		}
		if (b != 0) {
			if (a != A) {
				// b -> a
				DFS(a + Math.min(A - a, b) , b - Math.min(A - a, b), c, flag, set);
			}
			if (c != C) {
				// b -> c
				DFS(a, b - Math.min(C - c, b), c + Math.min(C - c, b), flag, set);
			}
		}
		if (c != 0) {
			if (a != A) {
				// c -> a
				DFS(a + Math.min(A - a, c), b, c - Math.min(A - a, c), flag, set);
			}
			if (b != B) {
				// c -> b
				DFS(a, b + Math.min(B - b, c), c - Math.min(B - b, c), flag, set);
			}
		}
	}

	public milk3() throws IOException {
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("milk3.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk3.out")));

		// Use StringTokenizer vs. readLine/split -- lots faster
		StringTokenizer st = new StringTokenizer(f.readLine());

	    this.A = Integer.parseInt(st.nextToken());
	    this.B = Integer.parseInt(st.nextToken());
	    this.C = Integer.parseInt(st.nextToken());
	    boolean[] flag = new boolean[C + 1];
	    DFS(0, 0, C, flag, new HashSet<String>());
	    for (int i = 0; i < C; i++) {
	    	if (flag[i]) {
	    		out.print(i + " ");
	    	}
	    }
	    out.println(C);
	    out.close();
	    f.close();
	}
	
	public static void main (String [] args) throws IOException {
		new milk3();
	}
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值