zoukankan      html  css  js  c++  java
  • 【扩展欧几里得】一步之遥

    题目:

    一步之遥
    从昏迷中醒来,小明发现自己被关在X星球的废矿车里。 
    矿车停在平直的废弃的轨道上。 
    他的面前是两个按钮,分别写着“F”和“B”。
    小明突然记起来,这两个按钮可以控制矿车在轨道上前进和后退。 
    按F,会前进97米。按B会后退127米。 
    透过昏暗的灯光,小明看到自己前方1米远正好有个监控探头。 
    他必须设法使得矿车正好停在摄像头的下方,才有机会争取同伴的援助。 
    或许,通过多次操作F和B可以办到。
    矿车上的动力已经不太足,黄色的警示灯在默默闪烁… 
    每次进行 F 或 B 操作都会消耗一定的能量。 
    小明飞快地计算,至少要多少次操作,才能把矿车准确地停在前方1米远的地方。
    请填写为了达成目标,最少需要操作的次数。
    注意,需要提交的是一个整数,不要填写任何无关内容(比如:解释说明等)

    思路:暴力搜索或者扩展欧几里得算法( 97x-127y=1  ax+by=m )

    代码:

     1 public class 一步之遥 {
     2 
     3     public static void main(String[] args) {
     4         // 解法一  扩展欧几里得算法
     5         try {
     6             long ans = ExtGcd.linearEquation(97, -127, 1);
     7             long x = ExtGcd.x;
     8             long y = ExtGcd.y;
     9             System.out.println(Math.abs(x) + Math.abs(y));   // 正确答案 97
    10         } catch (Exception e) {
    11             e.printStackTrace();
    12         }
    13         
    14         // 解法二 暴力搜索
    15         for (int i = 0; i < 100; i++) {
    16             for (int j = 0; j < 100; j++) {
    17                 if (97*i - 127*j == 1) {
    18                     System.out.println(Math.abs(i) + Math.abs(j));  // 正确答案 97
    19                     break;
    20                 }
    21             }
    22         }
    23         
    24     }
    25     
    26     // 私有的静态的内部类
    27     private static class ExtGcd{
    28         static long x,y;
    29         
    30         public static long ext_gcd(long a,long b){
    31             if (b==0) {
    32                 x = 1;
    33                 y = 0;
    34                 return a;
    35             }
    36             long res = ext_gcd(b, a%b);
    37             long x1 = x;
    38             x = y;
    39             y = x1-a/b*y;
    40             return res;
    41         }
    42         
    43         public static long linearEquation(long a,long b,long m) throws Exception{
    44             long d = ext_gcd(a, b);
    45             if(m%d!=0) throw new Exception("无解");
    46             long n = m / d;
    47             x *= n;
    48             y *= n;
    49             return d;
    50         }
    51     }
    52 
    53 }
  • 相关阅读:
    project 2013 激活 key 7YHNW-RVCQY-VBDB2-QX69Q-B96WK viso 66DNF-28W69-W4PPV-W3VYT-TJDBQ
    电脑快捷键
    Error (167005): Can't assign I/O pad "GX_TX" to PIN_AG27 because this causes failure in the placement of the other atoms in its associated channel
    学习资源
    数值孔径
    网络通信芯片
    DMD数字微镜
    运放输入阻抗
    DS18B20测温
    LED灯开关电路
  • 原文地址:https://www.cnblogs.com/xiaoyh/p/10331868.html
Copyright © 2011-2022 走看看