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
, and2
.The square room has walls of length
p
, and a laser ray from the southwest corner first meets the east wall at a distanceq
from the0
th 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.
Note:
1 <= p <= 1000
0 <= q <= p
典型的物理题搬到编程上面了,这个题的意思应该很清楚,一个正方形的房间(?),还是当作框吧,四壁都是玻璃,我们以左下角为坐标原点(0, 0)
,从远点发射一条光线,打在(p, q)
点上,然后光线反射,在其余三个顶点上有3个接收器,光线射在上面会被吸收,求最终射在哪个点上?
思考
这道题直接写模拟的话,反正我是写不出来的,我就是先在纸上画一下,将光线射在每一个点的情况分析清楚,首先画一个图就明白了:
图是win自带的工具画的,颜色代表序号,可见当以只有当光打在每个整数坐标处才有可能打到接受点,而且是不会打到发射点上的,从图中读出下列关系:
- x奇数,y偶数打到0
- x奇数,y奇数打到1
- x偶数,y奇数打到2
当然这些都是以p为单位长度的情况下满足的,即:
x∗p=k∗p x ∗ p = k ∗ p
y∗p=k∗q y ∗ p = k ∗ q
xmodp=ymodq=0 x mod p = y mod q = 0
那么这个题目就简化为求
k
k
了,问题就是了,而我们可以转化一下思路,
k∗q
k
∗
q
是q
和p
的倍数,可以直接转化为求p
、q
的最小公倍数,计算出来的最小公倍数除以
p
p
就是,
k
k
就是最小公倍数除以,从而计算出
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;
}
};
感想
思路有点复杂,有图就好多了。觉得不错点个赞可好?