如果找到规律,运行起来很快。
规律是:
两个杯子按大小排序,为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");
}
}