340 字
2 分钟
Carnival-Wheel

题面#

You have a prize wheel divided into ll sections, numbered from 00 to l1l-1. The sections are arranged in a circle, so after section l1l-1, the numbering continues again from section 00.

Initially, the prize pointer is at section aa. Each time you spin the wheel, the pointer moves exactly bb sections forward. That is, after one spin, the pointer moves from section aa to section (a+b)modl(a+b)\bmod l, after two spins to (a+2b)modl(a+2b)\bmod l, and so on ^{\text{∗}}.

You may spin the wheel any number of times (including zero). After you stop, the section where the pointer finally lands determines your prize: you receive an amount equal to the number of that section.

What is the maximum prize you can obtain?

^{\text{∗}}Here, xmodyx \bmod y denotes the remainder from dividing xx by yy.

Input

Each test contains multiple test cases. The first line contains the number of test cases tt (1t5001 \le t \le 500). The description of the test cases follows.

The first line of each test case contains three integers l,al, a, and bb (1l,b50001 \le l, b \le 5000, 0al10 \le a \le l-1).

Output

For each test case, output the maximum prize that can be obtained.

思路#

设旋转 kk 次落点为 xk=(a+kb)modlx_k=(a+k\cdot b)\bmod l

g=gcd(l,b)g=\gcd(l,b)xka(modg)x_k\equiv a\pmod g 因为 l0(modg)l\equiv 0\pmod gkb0(modg)k\cdot b\equiv 0\pmod g

所以所有可达落点都满足 xa(modg)x\equiv a\pmod g

l=l/g, b=b/gl'=l/g,\ b'=b/ggcd(l,b)=1\gcd(l',b')=1 因而 kbmodlk\cdot b'\bmod l' 可遍历 0l10\sim l'-1

r=amodgr=a\bmod g 则可达集合为 {r, r+g, r+2g, , r+(l1)g}\{r,\ r+g,\ r+2g,\ \dots,\ r+(l'-1)g\}
最大值为 r+(l1)g=r+lgr+(l'-1)g=r+l-g

每组直接输出 ans=lg+(amodg)\mathrm{ans}=l-g+(a\bmod g) 时间复杂度 O(1)O(1)

代码#

#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t --) {
int l, a, b;
cin >> l >> a >> b;
int g = gcd(l, b);
int r = a % g;
int ans = l - g + r;
cout << ans << endl;
}
}
Carnival-Wheel
https://github.com/posts/carnival-wheel/
作者
FZSGBall
发布于
2026-05-15
许可协议
CC BY-NC-SA 4.0