[Math_Medium] 858. Mirror Reflection

Posted qiulinzhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Math_Medium] 858. Mirror Reflection相关的知识,希望对你有一定的参考价值。

原题: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.)

技术分享图片

题目大意:

存在一个方形空间,如上图所示,一束光从左下角射出,方形空间的四条边都会反射,在0,1,2处存在3个接收器,问,给定方形空间的边长 p 和第一次到达右边界时距离0号接收器的距离,这束光最终会落到哪个接收器上?

解题思路

首先对于给定的p,q,如果我们把这两个数都同时放大N倍,光线的走法结果不会改变,因此,首先要找p,q得最大公约数,使得p,q互质;
然后,当p,q互质时,不可能两个都是偶数,因此分情况,当p为偶数,q为奇数时,光线会一直走右边界的奇数坐标(1,3,5,7....),然后再走左边的偶数坐标,因此最终必定会走到左边界,即2号接收器;若p为奇数,q为偶数,那么光线射到右边界时是偶数坐标,射到左边界时也是偶数坐标,而由于边长p是奇数,因此最终是不会走到左边界或右边界,即不会到接收器1和2,而是经过1,2之间的边界进行反向,然后往下走,而下面只有接收器0,因此最终必定会走到0;若p是奇数,且q也是奇数,那么光线到右边界时是奇数坐标,到左边界时是偶数坐标,因此最终一定走到接收器1。

代码:

class Solution {
public:
    int mirrorReflection(int p, int q) {
    int temp=gcd(p,q);
    p=p/temp;
    q=q/temp;
    if(p%2==0)
        return 2;
    else if(q%2==0)
        return 0;
    else
        return 1;
    }
    int gcd(int x,int y)
    {
        int m=x,n=y;
        int temp=0;
        while(n!=0)
        {
            temp=m%n;
            m=n;
            n=temp;
        }
        return m;
    }
};

以上




以上是关于[Math_Medium] 858. Mirror Reflection的主要内容,如果未能解决你的问题,请参考以下文章

[Math_Medium] 279. Perfect Squares 2018-09-19

[Math_Medium]553. Optimal Division

[Math_Medium]343. Integer Break

[Math_Medium] 592. Fraction Addition and Subtraction

[Math_Medium] 781. Rabbits in Forest

[Math_Medium]462. Minimum Moves to Equal Array Elements II