本身只是BFS搜尋,需要注意的有幾點:
1. 題目中的modulus操作與電腦的%不同。modulus(a,b) = (a%b+b)%b。 即保證結果一定為正。而電腦中是先abs(a)%b,再把a符號付給它。
2. 在搜尋過程中值會越來越大,不便於存入hash數組,由於計算的值總是用於比較modulus(tmp, K)==modulus(N+1,K),因此我們可以不必儲存tmp,而直接對tmp取modulus。
3. 由於存在modulus(tmp, M)的OP,因此要保證tmp一直還與M線性同餘。取tmp = modulus(tmp,KM),這樣既可以保證tmp比較小,又保證與K,M都線性同餘,使得之後的modulus(tmp,K)和modulus(tmp,M) 效果都與不對tmp進行任何處理效果相同。
4.注意Node中存的和hash的都是經過處理的tmp值。每次檢查是否得到正確結果,需要檢查 modulus(經過處理的tmp,K)==modulus(N+1,K)
import java.util.*;public class Main {String ops = "+-*%";class Node {int n;String path;}int N, K, M, result, KM;Scanner input = new Scanner(System.in);LinkedList<Node> list = new LinkedList<Node>();boolean[] hash = new boolean[1000001];public static void main(String[] args) {new Main().work();}public int modulus(int a, int b) {return (a % b + b) % b;}public void work() {while (input.hasNext()) {N = input.nextInt();K = input.nextInt();M = input.nextInt();if (N == 0 && K == 0 && M == 0) {break;}KM = K * M;list.clear();Arrays.fill(hash, false);Node head = new Node();head.path = "";head.n = N;hash[modulus(N, KM)] = true;result = modulus(N + 1, K);list.add(head);bfs();}input.close();}public void bfs() {while (!list.isEmpty()) {Node node = list.poll();if (modulus(node.n, K) == result) {System.out.println(node.path.length());System.out.println(node.path);return;}for (int i = 0; i < ops.length(); i++) {doOp(ops.charAt(i), node);}}System.out.println(0);}public void doOp(char op, Node node) {int tmp = 0;switch (op) {case '+':tmp = modulus(node.n + M, KM);break;case '-':tmp = modulus(node.n - M, KM);break;case '*':tmp = modulus(node.n * M, KM);break;case '%':tmp = modulus(modulus(node.n, M), KM);break;}if (!hash[tmp]) {hash[tmp] = true;Node newNode = new Node();newNode.path = node.path + op;newNode.n = tmp;list.addLast(newNode);}}}