zoukankan      html  css  js  c++  java
  • 第七届蓝桥杯大赛个人赛决赛(软件类C语言B组)第一题:一步之遥

     

    这题好多人用爆搜/bfs来做,然而这题可用exgcd(扩展欧几里得)做,而且很简便。

    先附原题:

    一步之遥

    从昏迷中醒来,小明发现自己被关在X星球的废矿车里。
    矿车停在平直的废弃的轨道上。
    他的面前是两个按钮,分别写着“F”和“B”。

    小明突然记起来,这两个按钮可以控制矿车在轨道上前进和后退。
    按F,会前进97米。按B会后退127米。
    透过昏暗的灯光,小明看到自己前方1米远正好有个监控探头。
    他必须设法使得矿车正好停在摄像头的下方,才有机会争取同伴的援助。
    或许,通过多次操作F和B可以办到。

    矿车上的动力已经不太足,黄色的警示灯在默默闪烁…
    每次进行 F 或 B 操作都会消耗一定的能量。
    小明飞快地计算,至少要多少次操作,才能把矿车准确地停在前方1米远的地方。

    请填写为了达成目标,最少需要操作的次数。

    注意,需要提交的是一个整数,不要填写任何无关内容(比如:解释说明等)

    【答案】97

    //法一:笔算(用数论exgcd的方法)
    ax + by = 1
    根据题意知 a = 97, b = -127
    按如下方式列出等式:
    -127 = -1 * 97 - 30
    97 = -3 * (-30) + 7
    -30 = -4 * 7 - 2
    7 = -3 * (-2) + 1
    -2 = 1 * (-2) + 0
    
    然后依照上面的式子开始整理,用含有a, b的式子表示上面的每个余数
    b = -a - 30
    -30 = a + b
    b = (-3) * (a + b) + 7
    7 = 4*a + 3*b
    ...
    ...
    这样一个个代入
    最终得到 55a + 42b =1
    操作的次数就是 55 + 42 = 97

    法二是写extendedEuclidean。

    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <cctype>
    #include <iostream>
    #include <algorithm>
    #include <map>
    #include <set>
    #include <vector>
    #include <string>
    
    using namespace std;
    
    long long extendedEuclidean(long long a, long long b, long long &x, long long &y)
    {
        if (!b) {
            x = 1; y = 0; return a;
        }
        long long g = extendedEuclidean(b, a % b, x, y);
        long long t = x - a / b * y;
        x = y;
        y = t;
        return g;
    }
    
    int main()
    {
        long long a, b;
        while (scanf("%lld%lld", &a, &b) == 2) {
            long long x = 1, y = 0;
            long long g = extendedEuclidean(a, b, x, y);
            while (x < 0) {
                x += b / g; y -= a / g;
            }
            cout << g << ' ' << '(' << x << ',' << y << ')' << endl;
        }
    
        return 0;
    }

     输入:

    97 -127

    输出:
    1 (55,42)

    ------------------

    55 + 42 = 97

  • 相关阅读:
    [LeetCode] 139. Word Break 单词拆分
    [LeetCode] 140. Word Break II 单词拆分II
    [LeetCode] 297. Serialize and Deserialize Binary Tree 二叉树的序列化和反序列化
    [LeetCode] 206. Reverse Linked List 反向链表
    [LeetCode] 92. Reverse Linked List II 反向链表II
    [LeetCode] 258. Add Digits 加数字
    [LeetCode] 66. Plus One 加一
    [LeetCode] 21. Merge Two Sorted Lists 合并有序链表
    [LeetCode] 88. Merge Sorted Array 合并有序数组
    [LeetCode] 10. Regular Expression Matching 正则表达式匹配
  • 原文地址:https://www.cnblogs.com/000what/p/10311664.html
Copyright © 2011-2022 走看看