• [编程题]饥饿的小易


    小易总是感觉饥饿,所以作为章鱼的小易经常出去寻找贝壳吃。最开始小易在一个初始位置x_0。对于小易所处的当前位置x,他只能通过神秘的力量移动到 4 * x + 3或者8 * x + 7。因为使用神秘力量要耗费太多体力,所以它只能使用神秘力量最多100,000次。贝壳总生长在能被1,000,000,007整除的位置(比如:位置0,位置1,000,000,007,位置2,000,000,014等)。小易需要你帮忙计算最少需要使用多少次神秘力量就能吃到贝壳。 

    输入描述:
    输入一个初始位置x_0,范围在1到1,000,000,006
    输出描述:
    输出小易最少需要使用神秘力量的次数,如果使用次数使用完还没找到贝壳,则输出-1
    输入例子:
    125000000
    输出例子:
    1

    算法思想:用哈希表存储已访问的点,使用队列存储待访问的点,bfs广度优先遍历

     1 import java.util.HashMap;
     2 import java.util.LinkedList;
     3 import java.util.Map;
     4 import java.util.Queue;
     5 import java.util.Scanner;
     6 
     7 public class Test23 {
     8     final static long MOD = 1000000007L;
     9     final static int MAX = 100000;
    10 
    11     public static void main(String[] args) {
    12 
    13         Scanner in = new Scanner(System.in);
    14         while (in.hasNextLong()) {
    15             long x = in.nextLong();
    16             System.out.println(count(x));
    17         }
    18     }
    19 
    20     private static long count(long x) {
    21         Map<Long, Integer> dist = new HashMap<Long, Integer>();//用哈希表存储已访问的点
    22         Queue<Long> queue = new LinkedList<Long>();//使用队列存储待访问的点,bfs广度优先遍历
    23         dist.put(x, 0);
    24         queue.add(x);
    25         while (!queue.isEmpty()) {
    26             long d;
    27             Long top = queue.poll();
    28             if (dist.get(top) > MAX)
    29                 break;
    30             if (top == 0) {
    31                 return dist.get(top);
    32             }
    33             d = ((top << 2) + 3) % MOD;
    34             if (d == 0) {
    35                 return dist.get(top) + 1;
    36             }
    37             if (!dist.containsKey(d)) {
    38                 queue.add(d);
    39                 dist.put(d, dist.get(top) + 1);
    40             }
    41             d = ((top << 3) + 7) % MOD;
    42             if (d == 0) {
    43                 return dist.get(top) + 1;
    44             }
    45             if (!dist.containsKey(d)) {
    46                 queue.add(d);
    47                 dist.put(d, dist.get(top) + 1);
    48             }
    49         }
    50         return -1L;
    51     }
    52 
    53 }


    Jumping from failure to failure with undiminished enthusiasm is the big secret to success.
  • 相关阅读:
    the configured user limit (128) on the number of inotify instances has been reached
    RabbitMQ Docker 单服务器集群
    webapi和GRPC性能对比
    camstart API 服务器负载均衡
    视图查询缺少值
    system.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0) 问题
    WCF 基础连接已经关闭: 服务器关闭了本应保持活动状态的连接。
    优化sql用到的方法
    调用C++动态链接库出现错误
    ThoughtWorks.QRCode源码
  • 原文地址:https://www.cnblogs.com/chongerlishan/p/5969142.html
Copyright © 2020-2023  润新知