【搜尋】HDU1104

來源:互聯網
上載者:User

本身只是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);}}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.