1. 程式人生 > >演算法競賽入門 例題7-1 最優程式

演算法競賽入門 例題7-1 最優程式

/*演算法競賽入門經典 例題7-1 最優程式 
 * BFS 棧和佇列
 * */
import java.util.LinkedList;
import java.util.Scanner;

class Node {
	String pre;// 之前的操作步驟
	int op;// 當前操作符 0:ADD, 1:SUB, 2:MUL, 3:DIV, 4:DUP
	LinkedList<Integer> stack = new LinkedList<Integer>();// 資料棧

	Node createNode() {//由當前節點創建出新節點
		Node node = new Node();
		node.pre = new String(this.pre);
		node.op = this.op;
		node.stack = new LinkedList<Integer>(this.stack);
		return node;
	}
}

public class BestProgram {
	static LinkedList<Node> queue = new LinkedList<Node>();
	static int a, b;
	static Node n = new Node();

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			a = scanner.nextInt();
			b = scanner.nextInt();
			queue.clear();
			dfs();
			System.out.println(n.pre);
		}
	}

	private static void dfs() {
		n.pre = "";
		n.op = 4;
		n.stack.push(a);
		queue.offer(n);
		while (queue.size() > 0) {
			n = queue.poll();
			op();
			int num = n.stack.getFirst();
			if (num == b)
				return;
			for (int i = 0; i < 5; i++) {
				Node node = n.createNode();
				node.op = i;
				switch (i) {
				case 0:
				case 1:
				case 2:
				case 3:
					if (node.stack.size() < 2)
						break;
					if (i == 3 && node.stack.getFirst() == 0)
						break;
				case 4:
					queue.offer(node);
				}
			}
		}
	}

	private static void op() {
		int s1 = 0, s2 = 0;
		if (n.op != 4) {
			s1 = n.stack.pop();
			s2 = n.stack.pop();
		} else {
			s1 = n.stack.getFirst();
		}
		switch (n.op) {
		case 0:
			n.stack.push(s1 + s2);
			n.pre += "ADD ";
			break;
		case 1:
			n.stack.push(s2 - s1);
			n.pre += "SUB ";
			break;
		case 2:
			n.stack.push(s1 * s2);
			n.pre += "MUL ";
			break;
		case 3:
			n.stack.push(s2 / s1);
			n.pre += "DIV ";
			break;
		case 4:
			n.stack.push(s1);
			n.pre += "DUP ";
			break;
		}
	}
}
輸入輸出示例
5 3
2 1000
2 3
2 4
DUP DIV DUP DUP ADD ADD 
DUP DUP ADD DUP ADD ADD DUP DUP MUL MUL 
DUP SUB MUL ADD 
DUP ADD