AcWing 222. 青蛙的约会
题目链接
设他们一共跳了 \(t\) 次,那么 A 青蛙跳到了 \((x+mt)\bmod L\),B 青蛙跳到了 \((y+nt)\bmod L\)
可列同余方程 \(x+mt\equiv y+nt\pmod L\)
可转化为 \(x+mt=y+nt+kL,(k\in Z)\)
整理得 \((m-n)t-Lk=y-x\)
这部分可由扩展欧几里得求出,当 \(\gcd(m-n,L)\nmid y-x\) 即不可能碰面。
题目要求求最小的,我们现在已经求出来其中一个解了,\(x=x_0+K\frac{b}{d},(d 表示 \gcd,K\in Z)\) 带入我们这道题得,\(ans=t+K\frac{L}{d}\) (这里得 \(t\) 是已经扩大了得,即 \(t='t\frac{y-x}{\gcd(m-n,L)}\))一开始我让我疑问的是,为什么这里(即 \(x=x_0+K\frac{b}{d}\))不能写成 \(x=x_0+Kb\) 后来经过思考才发现,这个解少了,精度太小了,所以才会让这道题 WA。
所以我们最后取模的数应是 \(\frac{b}{d}\)
\(\mathscr{Code:}\)
#include <bits/stdc++.h>
#define int long long
using namespace std;
#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
#define DEBUG(x) cerr << #x << " = " << x << '\n'
using LL = long long;
using ULL = unsigned long long;
typedef pair<int, int> PII;
inline LL read() {
LL s = 0, fu = 1; char ch = getchar();
while (ch < '0' || ch > '9') ch == '-' ? fu = -1 : 0, ch = getchar();
while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar();
return s * fu;
}
const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;
// const int N =
int x, y, m, n, L;
int exgcd(int a, int b, int &x, int &y) {
if (!b) {
x = 1, y = 0;
return a;
}
int d = exgcd(b, a % b, y, x);
y -= a / b * x;
return d;
}
signed main() {
x = read(), y = read(), m = read(), n = read(), L = read();
int a = m - n, b = L, x1, y1;
int d = exgcd(a, b, x1, y1);
if ((y - x) % d) puts("Impossible");
else {
x = (y - x) / d * x1;
int t = abs(L / d);
printf("%d\n", (x % t + t) % t);
}
return 0;
}

浙公网安备 33010602011771号