如果找到規律,運行起來很快。
規律是:
兩個杯子按大小排序,為S>M>N,
1.只要n滿了,就把n裡的東西放到s中
2.只要m非空,就把m中的放到n中
3.如果m為空白,把s中的放到m中。
但是這道題本意是讓機器來搜尋的。
用BFS,注意hash和剪枝。
Queue用Java內建的LinkedList。
HDU現在超好,有題目分類,有discuss,還能儲存你提交的代碼。就是題目有點少。
import java.util.Arrays;import java.util.LinkedList;import java.util.Scanner;public class Main { class Node { int[] max = new int[3];// S,M,N int[] v = new int[3]; int count; public Node clone() { Node node = new Node(); for (int i = 0; i < 3; i++) { node.max[i] = max[i]; node.v[i] = v[i]; node.count = count; } return node; } } Scanner input; boolean[] hash = new boolean[100 * 100 * 100 + 100 * 100 + 100]; LinkedList<Node> list = new LinkedList<Node>(); public static void main(String[] args) { new Main().work(); } public int hashing(Node node) { return node.v[0] * 10000 + node.v[1] * 100 + node.v[2]; } public void work() { input = new Scanner(System.in); while (input.hasNext()) { list.clear(); Arrays.fill(hash, false); Node head = new Node(); head.max[0] = input.nextInt(); head.max[1] = input.nextInt(); head.max[2] = input.nextInt(); head.v[0] = head.max[0]; head.count = 0; input.nextLine(); if (hashing(head) == 0) { break; } list.addLast(head); bfs(); } } public boolean check(Node node) { if ((node.v[0] == node.v[1] && node.v[2] == 0) || (node.v[0] == node.v[2] && node.v[1] == 0) || (node.v[0] == 0 && node.v[1] == node.v[2])) return true; return false; } public void bfs() { while (list.size() != 0) { Node node = list.poll(); for (int i = 0; i < 3; i++) { if (node.v[i] != 0) { for (int j = 0; j < 3; j++) { if (i == j || node.max[j]==node.v[j]) { continue; }else{ Node tmp = node.clone(); tmp.count++; if (tmp.v[i] >= (tmp.max[j] - tmp.v[j])) { tmp.v[i] -= (tmp.max[j] - tmp.v[j]); tmp.v[j] = tmp.max[j]; } else { tmp.v[j] += tmp.v[i]; tmp.v[i] = 0; } int hashV = hashing(tmp); if (!hash[hashV]) { if (check(tmp)) { System.out.println(tmp.count); return; } hash[hashV] = true; list.addLast(tmp); } } } } } } System.out.println("NO"); }}