LeetCode 858 Mirror Reflection

21 篇文章 0 订阅
20 篇文章 0 订阅

LeetCode 858 Mirror Reflection

传送门

题目分析

There is a special square room with mirrors on each of the four walls. Except for the southwest corner, there are receptors on each of the remaining corners, numbered 0, 1, and 2.

The square room has walls of length p, and a laser ray from the southwest corner first meets the east wall at a distance q from the 0th receptor.

Return the number of the receptor that the ray meets first. (It is guaranteed that the ray will meet a receptor eventually.)

Example 1:

Input: p = 2, q = 1
Output: 2
Explanation: The ray meets receptor 2 the first time it gets reflected back to the left wall.

jpg

Note:

  1. 1 <= p <= 1000
  2. 0 <= q <= p

典型的物理题搬到编程上面了,这个题的意思应该很清楚,一个正方形的房间(?),还是当作框吧,四壁都是玻璃,我们以左下角为坐标原点(0, 0),从远点发射一条光线,打在(p, q)点上,然后光线反射,在其余三个顶点上有3个接收器,光线射在上面会被吸收,求最终射在哪个点上?

思考

这道题直接写模拟的话,反正我是写不出来的,我就是先在纸上画一下,将光线射在每一个点的情况分析清楚,首先画一个图就明白了:

grid

图是win自带的工具画的,颜色代表序号,可见当以只有当光打在每个整数坐标处才有可能打到接受点,而且是不会打到发射点上的,从图中读出下列关系:

  • x奇数,y偶数打到0
  • x奇数,y奇数打到1
  • x偶数,y奇数打到2

当然这些都是以p为单位长度的情况下满足的,即:

xp=kp x ∗ p = k ∗ p

yp=kq y ∗ p = k ∗ q

xmodp=ymodq=0 x mod p = y mod q = 0

那么这个题目就简化为求 k k 了,问题就是了kq,而我们可以转化一下思路, kq k ∗ q qp的倍数,可以直接转化为求pq的最小公倍数,计算出来的最小公倍数除以 p p 就是y k k 就是最小公倍数除以q,从而计算出 x x <script type="math/tex" id="MathJax-Element-44">x</script>。

代码实现

using ll = long long;

ll gcd(ll a, ll b) {
    while (b) {
        ll t = a % b;
        a = b;
        b = t;
    }
    return a;
}

class Solution {
public:
    int mirrorReflection(int p, int q) {
        ll x = 0, y = 0;
        // 最小公倍数
        ll g = p * q / gcd(p, q);
        y = g / p;
        x = g / q;
        if (x % 2 == 1 && y % 2 == 0) {
            return 0;
        }
        else if (x % 2 == 1 && y % 2 == 1) {
            return 1;
        }
        else if (x % 2 == 0 && y % 2 == 1) {
            return 2;
        }
        return 0;
    }
};

感想

思路有点复杂,有图就好多了。觉得不错点个赞可好?

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值