Specular reflection LeetCode 858

topic

There is a special square room, each wall has a mirror. In addition to the southwest corner, every corner placed a receiver, numbered 0, 1, and 2.

Length of the room walls of a square of p, a laser beam emitted from the southwest corner, will first encounter with the east wall, the point of incidence to the receiver distance from 0 to q.

Returning light receiver numbered first encountered (guaranteed ultimately encounter a light receiver).

Thinking

If this problem relying solely on specular reflection of thinking is very difficult to solve complex problems, the problem must be transformed.
1. We assume two things infinite wall stretched north, the north wall being ignored, so that only the light reflected upward.
2. When the longitudinal direction of the first distance is an integer multiple of p, which may be considered to reach a light receiver.
3 can be found by looking at the drawing, the vertical distance is the least common multiple of p and q, is set to s.
4. How to judge which receives the light encounters? In two steps
. A first determine the light reaches the brick wall or the north wall (Analyzing s / p parity);
. If a brick wall B (s / p is even) the receiver directly back to 0; if the north wall (s / p is an odd ) needed to determine the receptacle 1 or 2 (Analyzing s / q parity);

Code

class Solution {
public:
    int mirrorReflection(int p, int q) {
        int s=lcm(p,q);//最小公倍数等于纵向距离
        if((s/p)%2==0){//若南北次数为偶,则为南墙,0
            return 0;
        }
        else{//为奇北墙
            if((s/q%2)==1)return 1;//若东西次数为奇,则东墙,1
            else return 2;//为偶西墙,2
        }
    }
    int gcd(int a, int b){//最大公约数
        return a % b ? gcd(b, a % b) : b;
    }
    int lcm(int a, int b){//最小公倍数
        return a * b / gcd(a, b);
    }
};

Guess you like

Origin www.cnblogs.com/ambassdor/p/12240658.html