题面
来源:USACO 官网。模型收到的是同一份题面的文字。
Answer $Q$ ($1\le Q\le 10^5$) independent queries each of the following form:
You are given four integers $a,b,c,d$ ($-10^{18}\le a,b,c,d\le 10^{18}$). In one operation you can either do $a\mathrel{+}=b$, or $b\mathrel{+}=a$. Determine the minimum number of operations to transform $(a,b)$ into $(c,d)$, or if it is impossible to do so, output $-1$.
INPUT FORMAT (input arrives from the terminal / stdin):
The first line contains $Q$.The next $Q$ lines each contain four integers $a,b,c,d$.
OUTPUT FORMAT (print output to the terminal / stdout):
The answer for each query on a separate line.SAMPLE INPUT:
4 5 -3 -1 -3 5 3 5 2 5 3 8 19 5 3 5 3
SAMPLE OUTPUT:
2 -1 3 0
First query: $(5,-3)\to (2,-3)\to (-1,-3)$
Second query: Impossible.
Third query: $(5,3) \to (8, 3) \to (8, 11) \to (8, 19)$
Fourth query: No operations necessary.
SCORING:
- Input 2: $|a|, |b|, |c|,|d|\le 10$
- Input 3: $a,b\ge 0$
- Input 4: $a \geq 0 \geq b$
- Input 5: $a \leq 0 \leq b$
- Input 6: $a,b\le 0$
- Input 7: $c,d\ge 0$
- Input 8: $c \geq 0 \geq d$
- Input 9: $c \leq 0 \leq d$
- Input 10: $c,d\le 0$
- Inputs 11-14: $Q \leq 10^3$
- Inputs 15-19: No additional constraints.
Problem credits: Benjamin Qi
结果
Kimi K3.1 ProKimi
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 42.3k平均输出 token(含思考) ↓
- 25.1输出速度 tokens/s ↑
- 1496 秒延迟 ↓
- 1.16×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
Kimi K3.1 Pro(high)Kimi high
2/3
解出的采样 ↑
- 78.9采样 1 · 答案错误
- 100采样 2 · 解出
- 100采样 3 · 解出
- 33.4k平均输出 token(含思考) ↓
- 26.0输出速度 tokens/s ↑
- 1219 秒延迟 ↓
- 0.92×CPU 时间 / 官方解 ↓
- 同阶 2时间复杂度(相对官方解)
DeepSeek Flash V4.1-1017DeepSeek
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 67.9k平均输出 token(含思考) ↓
- 132.2输出速度 tokens/s ↑
- 536 秒延迟 ↓
- 1.25×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
MiniMax M3.1 FlashMiniMax
3/3
解出的采样 ↑
- 100采样 1 · 解出
- 100采样 2 · 解出
- 100采样 3 · 解出
- 67.7k平均输出 token(含思考) ↓
- 165.4输出速度 tokens/s ↑
- 397 秒延迟 ↓
- 0.57×CPU 时间 / 官方解 ↓
- 同阶 3时间复杂度(相对官方解)
↑ 越大越好,↓ 越小越好。得分 0–100,按官方时限判定,所有测试点都满分才算解出。CPU 时间 / 官方解为解出的答案在官方解最慢的 3 个测试点上的 CPU 时间之比(几何平均),只比较官方解至少需要 0.05 秒的题;复杂度按增长幂次相对官方解分类。判题与计分见 原理。
代码
#include <bits/stdc++.h> using namespace std; using ll = long long; using i128 = __int128_t; static inline ll absll(ll x) { return x >= 0 ? x : -x; } // Coefficients for abs(A), abs(B), then adjusted for their signs. static pair<i128, i128> bezout(ll A, ll B) { ll r0 = absll(A), r1 = absll(B); i128 x0 = 1, x1 = 0, y0 = 0, y1 = 1; while (r1 != 0) { ll q = r0 / r1; ll nr = r0 % r1; r0 = r1; r1 = nr; i128 nx = x0 - (i128)q * x1; i128 ny = y0 - (i128)q * y1; x0 = x1; x1 = nx; y0 = y1; y1 = ny; } if (A < 0) x0 = -x0; if (B < 0) y0 = -y0; return {x0, y0}; } // b is positive. static i128 floorDiv(i128 a, i128 b) { i128 q = a / b; if (a % b < 0) --q; return q; } // b is positive. static i128 ceilDiv(i128 a, i128 b) { i128 q = a / b; if (a % b > 0) ++q; return q; } static string toString(i128 x) { if (x == 0) return "0"; bool neg = x < 0; if (neg) x = -x; string s; while (x > 0) { s.push_back(char('0' + int(x % 10))); x /= 10; } if (neg) s.push_back('-'); reverse(s.begin(), s.end()); return s; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { ll a, b, c, d; cin >> a >> b >> c >> d; if (a == c && b == d) { cout << "0\n"; continue; } if (a == 0 && b == 0) { cout << "-1\n"; continue; } ll g = std::gcd(absll(a), absll(b)); if (std::gcd(absll(c), absll(d)) != g) { cout << "-1\n"; continue; } // Reduce to primitive vectors. ll A = a / g, B = b / g; ll C = c / g, D = d / g; auto [u, v] = bezout(A, B); // u*A + v*B = 1 auto [z, t] = bezout(C, D); // z*C + t*D = 1 /* Every integer determinant-one matrix taking (A,B) to (C,D) has the form M_k = Q * L^k * P^(-1), where L = [[1,1],[0,1]]. Its entries are affine in k. We need exactly those k for which all entries are nonnegative; such a matrix, and only such a matrix, is a product of the two operation matrices. */ i128 p0 = (i128)C * u + (i128)t * B; i128 q0 = (i128)C * v - (i128)t * A; i128 r0 = (i128)D * u - (i128)z * B; i128 s0 = (i128)D * v + (i128)z * A; i128 cp = -(i128)C * B; i128 cq = (i128)C * A; i128 cr = -(i128)D * B; i128 cs = (i128)D * A; bool ok = true, hasLo = false, hasHi = false; i128 lo = 0, hi = 0; auto addConstraint = [&](i128 base, i128 coef) { if (!ok) return; if (coef == 0) { if (base < 0) ok = false; } else if (coef > 0) { i128 bound = ceilDiv(-base, coef); if (!hasLo || bound > lo) { lo = bound; hasLo = true; } } else { i128 bound = floorDiv(base, -coef); if (!hasHi || bound < hi) { hi = bound; hasHi = true; } } }; addConstraint(p0, cp); addConstraint(q0, cq); addConstraint(r0, cr); addConstraint(s0, cs); if (!ok || (hasLo && hasHi && lo > hi)) { cout << "-1\n"; continue; } // Factor a nonnegative SL(2,Z) matrix into the two operation // matrices, batching consecutive identical factors. auto wordLength = [&](i128 k) -> i128 { i128 p = p0 + cp * k; i128 q = q0 + cq * k; i128 r = r0 + cr * k; i128 s = s0 + cs * k; if (p < 0 || q < 0 || r < 0 || s < 0) return -1; i128 ans = 0; while (true) { if (q == 0) { // R^r ans += r; break; } if (r == 0) { // L^q ans += q; break; } i128 n; if (p >= r && q >= s) { // The last factors are L: subtract the second row // from the first row. n = std::min(p / r, q / s); if (n <= 0) return -1; p -= n * r; q -= n * s; } else { // The last factors are R: subtract the first row // from the second row. n = std::min(r / p, s / q); if (n <= 0) return -1; r -= n * p; s -= n * q; } ans += n; } return ans; }; i128 best = -1; auto tryK = [&](i128 k) { i128 len = wordLength(k); if (len >= 0 && (best < 0 || len < best)) best = len; }; // The shortest representation occurs at an endpoint of the // feasible interval. Normally there is only one finite endpoint. if (hasLo) tryK(lo); if (hasHi && (!hasLo || hi != lo)) tryK(hi); if (!hasLo && !hasHi) tryK(0); if (best < 0) cout << "-1\n"; else cout << toString(best) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll INF = LLONG_MAX; // a,b > 0 and c,d > 0. All intermediate states must remain positive. ll positiveCore(ll a, ll b, ll c, ll d) { ll answer = 0; while (true) { if (c < a || d < b) return -1; if (a == c && b == d) return answer; if (c == d) return -1; if (c < d) { swap(a, b); swap(c, d); continue; } // Now c > d. The last reverse operations are forced to be c -= d. if (d == b && (c - a) % d == 0) { return answer + (c - a) / d; } // Reduce c to a value in [1,d], unless this would overshoot a. ll steps = (c - 1) / d; ll maximumSteps = (c - a) / d; if (steps > maximumSteps) return -1; c -= steps * d; answer += steps; } } // Nonnegative initial state, with a nonnegative target. ll nonnegative(ll a, ll b, ll c, ll d) { if (c < a || d < b) return -1; if (a == c && b == d) return 0; if (a == 0 && b == 0) return -1; if (a == 0) { // To make the first coordinate nonzero, (0,b) -> (b,b) is forced. if (c == 0) return -1; ll result = positiveCore(b, b, c, d); return result < 0 ? -1 : result + 1; } if (b == 0) { if (d == 0) return -1; ll result = positiveCore(a, a, c, d); return result < 0 ? -1 : result + 1; } return positiveCore(a, b, c, d); } struct FSeg { ll x, y; // Candidates are z = x-k*y, second coordinate z-y. ll maxK; ll prefix; ll minZ, maxZ; }; struct BSeg { ll u, v; // Candidates are (u-t*v,v). ll maxT; ll prefix; ll minZ, maxZ; }; // Candidates for crossing from (x,-y), x>y, to the positive pair (x,x-y). vector<FSeg> buildForwardSegments(ll A, ll B) { vector<FSeg> segments; segments.reserve(128); ll x = A, y = B, prefix = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; ll maxK = r ? q - 1 : q - 2; if (maxK >= 0) { ll minZ = x - maxK * y; segments.push_back({x, y, maxK, prefix, minZ, x}); } if (r) { prefix += q; x = r; } else { break; } } else { ll q = y / x; ll r = y % x; if (r) { prefix += q; y = r; } else { break; } } } return segments; } // Positive ancestors of the target which can serve as a crossing state. vector<BSeg> buildBackwardSegments(ll C, ll D) { vector<BSeg> segments; segments.reserve(128); ll x = C, y = D, prefix = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; ll maxT = r ? q - 1 : q - 2; if (maxT >= 0) { ll minZ = x - maxT * y; segments.push_back({x, y, maxT, prefix, minZ, x}); } if (r) { prefix += q; x = r; } else { break; } } else { ll q = y / x; ll r = y % x; if (r) { prefix += q; y = r; } else { break; } } } return segments; } // Reach (g,-g), where g = gcd(A,B), using only sign-preserving operations. pair<ll, ll> equalStateInfo(ll A, ll B) { ll x = A, y = B, distance = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; if (r) { distance += q; x = r; } else { distance += q - 1; x = y; } } else { ll q = y / x; ll r = y % x; if (r) { distance += q; y = r; } else { distance += q - 1; y = x; } } } return {x, distance}; } // Target is still in the quadrant (positive,negative). ll oppositeDistance(ll A, ll B, ll C, ll D) { ll x = A, y = B, prefix = 0; while (true) { if (x == C && y == D) return prefix; if (x == y) return -1; if (x > y) { ll q = x / y; ll r = x % y; ll steps = r ? q : q - 1; ll endX = r ? r : y; if (D == y && C <= x && C >= endX && (x - C) % y == 0) { ll k = (x - C) / y; if (k <= steps) return prefix + k; } prefix += steps; x = endX; } else { ll q = y / x; ll r = y % x; ll steps = r ? q : q - 1; ll endY = r ? r : x; if (C == x && D <= y && D >= endY && (y - D) % x == 0) { ll k = (y - D) / x; if (k <= steps) return prefix + k; } prefix += steps; y = endY; } } } // Start is (A,-B), A,B>0; target is strictly positive. ll crossToPositive(ll A, ll B, ll C, ll D) { ll best = INF; // Route through (g,-g), then (g,0), followed by nonnegative operations. auto [g, toEqual] = equalStateInfo(A, B); ll viaZero = nonnegative(g, 0, C, D); if (viaZero >= 0) { best = toEqual + 1 + viaZero; } vector<FSeg> forward = buildForwardSegments(A, B); vector<BSeg> backward = buildBackwardSegments(C, D); // Both lists consist of disjoint intervals, ordered by decreasing z. size_t i = 0, j = 0; while (i < forward.size() && j < backward.size()) { const FSeg &f = forward[i]; const BSeg &b = backward[j]; if (f.minZ > b.maxZ) { ++i; continue; } if (b.minZ > f.maxZ) { ++j; continue; } // Equality of second coordinates gives z-y = v, hence z = y+v. ll z = f.y + b.v; if (z >= f.minZ && z <= f.maxZ && z >= b.minZ && z <= b.maxZ && (f.x - z) % f.y == 0 && (b.u - z) % b.v == 0) { ll k = (f.x - z) / f.y; ll t = (b.u - z) / b.v; ll total = f.prefix + k + 1 + b.prefix + t; best = min(best, total); } if (f.minZ > b.minZ) { ++i; } else if (f.minZ < b.minZ) { ++j; } else { ++i; ++j; } } return best == INF ? -1 : best; } ll solveQuery(ll a, ll b, ll c, ll d) { if (a == 0 && b == 0) { return (c == 0 && d == 0) ? 0 : -1; } if (a >= 0 && b >= 0) { if (c < 0 || d < 0) return -1; return nonnegative(a, b, c, d); } if (a <= 0 && b <= 0) { if (c > 0 || d > 0) return -1; return nonnegative(-a, -b, -c, -d); } // Normalize the opposite-sign start to a>0, b<0. if (a < 0) { swap(a, b); swap(c, d); } ll A = a; ll B = -b; if (c > 0 && d < 0) { return oppositeDistance(A, B, c, -d); } if (c < 0 && d > 0) { return -1; } if (c > 0 && d > 0) { return crossToPositive(A, B, c, d); } if (c < 0 && d < 0) { // Negate everything and swap coordinates. return crossToPositive(B, A, -d, -c); } // A target with a zero coordinate can only be reached immediately after // arriving at (g,-g). auto [g, toEqual] = equalStateInfo(A, B); if ((c == g && d == 0) || (c == 0 && d == -g)) { return toEqual + 1; } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { ll a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; using i128 = __int128_t; struct Run { int64 x, y; // First pair in this run int64 start; // Global index of the first pair int64 n; // Number of pairs in the run int64 lo, hi; // Depth interval of these pairs bool horizontal; // x > y }; struct RunInfo { vector<Run> runs; int64 depth = 0; int64 root = 0; }; static int64 abs64(int64 x) { return x < 0 ? -x : x; } // Compressed list of all non-root ancestors of (x,y), including (x,y). // A run with x>y contains (x-t*y,y); one with y>x contains (x,y-t*x). static RunInfo buildRuns(int64 x, int64 y) { RunInfo info; int64 index = 0; while (x != y) { Run r; r.x = x; r.y = y; r.start = index; r.horizontal = (x > y); if (x > y) { int64 q = x / y; r.n = (x % y == 0 ? q - 1 : q); x -= r.n * y; } else { int64 q = y / x; r.n = (y % x == 0 ? q - 1 : q); y -= r.n * x; } index += r.n; info.runs.push_back(r); } info.depth = index; info.root = x; // x == y == gcd of the original pair for (Run &r : info.runs) { r.hi = info.depth - r.start; r.lo = r.hi - r.n + 1; } return info; } // Number of parent steps from the pair used to build info to anc, // or -1 if anc is not an ancestor. static int64 ancestorDist(const RunInfo &info, pair<int64,int64> anc) { for (const Run &r : info.runs) { if (r.horizontal) { if (anc.second == r.y && anc.first > r.y && anc.first <= r.x) { int64 diff = r.x - anc.first; if (diff % r.y == 0) { int64 t = diff / r.y; if (t < r.n) return r.start + t; } } } else { if (anc.first == r.x && anc.second > r.x && anc.second <= r.y) { int64 diff = r.y - anc.second; if (diff % r.x == 0) { int64 t = diff / r.x; if (t < r.n) return r.start + t; } } } } if (anc.first == info.root && anc.second == info.root) return info.depth; return -1; } static int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { // Zero initial states: one useful operation reaches (s,s), after which // the ordinary same-sign process applies. if (a == 0 || b == 0) { if (a == 0 && b == 0) return (c == 0 && d == 0) ? 0 : -1; if (a == c && b == d) return 0; int64 s = (b == 0 ? a : b); bool correctSign = (s > 0 && c > 0 && d > 0) || (s < 0 && c < 0 && d < 0); if (!correctSign) return -1; int64 x = abs64(c), y = abs64(d); if (std::gcd(x, y) != abs64(s)) return -1; RunInfo target = buildRuns(x, y); return target.depth + 1; } // Both initial components have the same sign. if ((a > 0 && b > 0) || (a < 0 && b < 0)) { bool correctSign = (a > 0 && c > 0 && d > 0) || (a < 0 && c < 0 && d < 0); if (!correctSign) return -1; pair<int64,int64> start = {abs64(a), abs64(b)}; pair<int64,int64> target = {abs64(c), abs64(d)}; RunInfo info = buildRuns(target.first, target.second); return ancestorDist(info, start); } // Canonicalize an opposite-sign start to a>0>b. Swapping both pairs // preserves operation counts. if (a < 0) { swap(a, b); swap(c, d); } int64 x = a, y = -b; RunInfo startInfo = buildRuns(x, y); int64 g = startInfo.root; // Zero targets are reachable only through (g,-g). if (c == 0 || d == 0) { if ((c == 0 && d == -g) || (c == g && d == 0)) return startInfo.depth + 1; return -1; } // Still opposite signs: only the deterministic non-crossing chain applies. if (c > 0 && d < 0) { return ancestorDist(startInfo, {c, -d}); } if (c < 0 && d > 0) return -1; // The target has equal signs. Normalize to positive absolute values. bool positiveTarget = (c > 0); int64 tx = abs64(c), ty = abs64(d); if (std::gcd(tx, ty) != g) return -1; RunInfo targetInfo = buildRuns(tx, ty); // Fallback: go to (g,-g), then through a zero state to (g,g) or (-g,-g), // and finally follow the same-sign path to the target. i128 best = (i128)startInfo.depth + targetInfo.depth + 2; // A crossing at a non-root ancestor (x,y), x>y, produces the positive // base (x,x-y). At x<y it produces the negative base with absolute // values (y-x,y). Match all such bases against ancestors of the target. const auto &S = startInfo.runs; const auto &T = targetInfo.runs; size_t i = 0, j = 0; while (i < S.size() && j < T.size()) { const Run &s = S[i]; const Run &t = T[j]; bool overlap = !(s.hi < t.lo || t.hi < s.lo); if (!overlap) { if (s.lo > t.hi) ++i; else ++j; continue; } // Positive bases come from horizontal runs, negative ones from // vertical runs. Equal pairs must also have the same orientation. if (s.horizontal == positiveTarget && s.horizontal == t.horizontal) { if (s.horizontal) { // Base: (s.x-k*s.y, s.x-(k+1)*s.y) // Target run: (t.x-l*t.y, t.y) int64 diff = s.x - t.y; if (diff > 0 && diff % s.y == 0) { int64 h = diff / s.y; // h = k+1 if (h >= 1 && h <= s.n) { int64 k = h - 1; int64 baseX = s.x - k * s.y; int64 diff2 = t.x - baseX; if (diff2 >= 0 && diff2 % t.y == 0) { int64 l = diff2 / t.y; if (l < t.n) { i128 cost = (i128)s.start + k + 1 + t.start + l; if (cost < best) best = cost; } } } } } else { // Base: (s.y-(k+1)*s.x, s.y-k*s.x) // Target run: (t.x, t.y-l*t.x) int64 diff = s.y - t.x; if (diff > 0 && diff % s.x == 0) { int64 h = diff / s.x; // h = k+1 if (h >= 1 && h <= s.n) { int64 k = h - 1; int64 baseY = s.y - k * s.x; int64 diff2 = t.y - baseY; if (diff2 >= 0 && diff2 % t.x == 0) { int64 l = diff2 / t.x; if (l < t.n) { i128 cost = (i128)s.start + k + 1 + t.start + l; if (cost < best) best = cost; } } } } } } // Enumerate only pairs of runs whose depth intervals overlap. if (s.lo > t.lo) ++i; else if (t.lo > s.lo) ++j; else { ++i; ++j; } } return (int64)best; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; using i128 = __int128_t; const int64 INF = numeric_limits<int64>::max(); // A segment represents consecutive states of a subtractive Euclidean chain. // dir = 0: (x - t*y, y), 0 <= t <= m // dir = 1: (x, y - t*x), 0 <= t <= m // dir = -1: terminal state (g,g) struct Segment { int64 x, y, m, k; int dir; int64 hi, lo; // Range of coordinate sums in this segment. }; struct Chain { vector<Segment> seg; int64 g; int64 steps; }; Chain buildChain(int64 x, int64 y) { Chain ch; ch.seg.reserve(128); int64 k = 0; while (x != y) { Segment s; s.x = x; s.y = y; s.k = k; s.hi = x + y; int64 nx = x, ny = y; if (x > y) { s.dir = 0; s.m = (x - 1) / y; nx = x - s.m * y; s.lo = nx + y; } else { s.dir = 1; s.m = (y - 1) / x; ny = y - s.m * x; s.lo = x + ny; } ch.seg.push_back(s); x = nx; y = ny; k += s.m; } Segment terminal{x, y, 0, k, -1, x + y, x + y}; ch.seg.push_back(terminal); ch.g = x; ch.steps = k; return ch; } // Returns the number of reverse operations at which (x,y) occurs, // or -1 if it does not occur in the chain. int64 findInChain(const Chain& ch, int64 x, int64 y) { for (const Segment& s : ch.seg) { if (s.dir == -1) { if (x == s.x && y == s.y) return s.k; continue; } if (s.dir == 0) { if (y != s.y || x > s.x) continue; int64 diff = s.x - x; if (diff % s.y != 0) continue; int64 t = diff / s.y; if (t <= s.m) return s.k + t; } else { if (x != s.x || y > s.y) continue; int64 diff = s.y - y; if (diff % s.x != 0) continue; int64 t = diff / s.x; if (t <= s.m) return s.k + t; } } return -1; } // Both initial coordinates are nonnegative. int64 solveNonnegative(int64 a, int64 b, int64 c, int64 d) { if (a == c && b == d) return 0; if (a == 0 && b == 0) return -1; if (a == 0) { if (c == 0 || d == 0) return -1; Chain target = buildChain(b, b); int64 suffix = findInChain(target, c, d); return suffix < 0 ? -1 : suffix + 1; } if (b == 0) { if (c == 0 || d == 0) return -1; Chain target = buildChain(a, a); int64 suffix = findInChain(target, c, d); return suffix < 0 ? -1 : suffix + 1; } if (c <= 0 || d <= 0) return -1; Chain target = buildChain(c, d); return findInChain(target, a, b); } // A candidate segment corresponds to possible exits from the mixed-sign // prefix. Its states are obtained from states of the target's positive chain. struct Candidate { int64 x, y, m, k; int64 hi, lo; // Range of sums of the associated mixed-chain state. }; // Try to intersect one mixed-prefix segment and one candidate segment. bool intersectSegments(const Segment& s, const Candidate& c, int mode, int64& answer) { i128 t = 0; bool ok = true; if (s.dir == 0) { // The second coordinate of the mixed-chain state is fixed. if (mode == 0) { // p2 = c.x - (t+1)*c.y = s.y i128 num = (i128)c.x - s.y; if (num < 0 || num % c.y != 0) ok = false; else t = num / c.y - 1; } else { // p2 = c.y - t*c.x = s.y i128 num = (i128)c.y - s.y; if (num < 0 || num % c.x != 0) ok = false; else t = num / c.x; } } else if (s.dir == 1) { // The first coordinate of the mixed-chain state is fixed. if (mode == 0) { // p1 = c.x - t*c.y = s.x i128 num = (i128)c.x - s.x; if (num < 0 || num % c.y != 0) ok = false; else t = num / c.y; } else { // p1 = c.y - (t+1)*c.x = s.x i128 num = (i128)c.y - s.x; if (num < 0 || num % c.x != 0) ok = false; else t = num / c.x - 1; } } else { ok = false; } if (!ok || t < 0 || t >= c.m) return false; int64 tt = (int64)t; i128 p1, p2; if (mode == 0) { p1 = (i128)c.x - (i128)tt * c.y; p2 = (i128)c.x - (i128)(tt + 1) * c.y; } else { p1 = (i128)c.y - (i128)(tt + 1) * c.x; p2 = (i128)c.y - (i128)tt * c.x; } i128 prefixOffset; if (s.dir == 0) { if (p2 != s.y || p1 > s.x) return false; i128 diff = (i128)s.x - p1; if (diff < 0 || diff % s.y != 0) return false; prefixOffset = diff / s.y; } else { if (p1 != s.x || p2 > s.y) return false; i128 diff = (i128)s.y - p2; if (diff < 0 || diff % s.x != 0) return false; prefixOffset = diff / s.x; } if (prefixOffset < 0 || prefixOffset > s.m) return false; i128 cost = (i128)s.k + prefixOffset + 1 + c.k + tt; answer = (int64)cost; return true; } // mode 0: positive target, exit state (X,Y) has X>Y. // mode 1: negative target (use its negation), exit state has X<Y. int64 solveSignedTarget(const Chain& mixed, const Chain& target, int mode) { vector<Candidate> candidates; candidates.reserve(64); for (const Segment& s : target.seg) { if ((mode == 0 && s.dir == 0) || (mode == 1 && s.dir == 1)) { if (s.m == 0) continue; Candidate c; c.x = s.x; c.y = s.y; c.m = s.m; // Candidates are t=0,...,m-1. c.k = s.k; i128 hi, lo; if (mode == 0) { hi = (i128)2 * s.x - s.y; lo = hi - (i128)2 * (s.m - 1) * s.y; } else { hi = (i128)2 * s.y - s.x; lo = hi - (i128)2 * (s.m - 1) * s.x; } c.hi = (int64)hi; c.lo = (int64)lo; candidates.push_back(c); } } int64 best = INF; size_t i = 0, j = 0; // Coordinate sums decrease along both sequences. Merge their intervals; // the first intersection also minimizes prefix length + suffix length. while (i < mixed.seg.size() && j < candidates.size()) { const Segment& s = mixed.seg[i]; if (s.dir == -1) break; const Candidate& c = candidates[j]; if (c.lo > s.hi) { ++j; continue; } if (s.lo > c.hi) { ++i; continue; } int64 cost; if (intersectSegments(s, c, mode, cost)) { best = cost; break; } if (s.lo > c.lo) ++i; else if (c.lo > s.lo) ++j; else { ++i; ++j; } } // At the terminal mixed state (g,-g), one can instead pass through an // axis state and start the monotone suffix from (g,g), or from (-g,-g). if (mixed.g == target.g) { i128 special = (i128)mixed.steps + 2 + target.steps; best = min(best, (int64)special); } return best == INF ? -1 : best; } int64 solveMixed(int64 a, int64 b, int64 c, int64 d) { // Canonicalize to a > 0 > b. Swapping coordinates preserves the answer. if (a < 0) { swap(a, b); swap(c, d); } Chain mixed = buildChain(a, -b); if (c > 0 && d < 0) { // The target lies on the deterministic mixed-sign prefix itself. return findInChain(mixed, c, -d); } if (c < 0 && d > 0) return -1; if (c > 0 && d > 0) { Chain target = buildChain(c, d); return solveSignedTarget(mixed, target, 0); } if (c < 0 && d < 0) { Chain target = buildChain(-c, -d); return solveSignedTarget(mixed, target, 1); } // A zero coordinate can first appear only from the terminal state (g,-g). if (c == 0 && d < 0 && d == -mixed.g) return mixed.steps + 1; if (d == 0 && c > 0 && c == mixed.g) return mixed.steps + 1; return -1; } int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { if (a >= 0 && b >= 0) { if (c < 0 || d < 0) return -1; return solveNonnegative(a, b, c, d); } if (a <= 0 && b <= 0) { if (c > 0 || d > 0) return -1; return solveNonnegative(-a, -b, -c, -d); } return solveMixed(a, b, c, d); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll INF = LLONG_MAX; // a,b > 0 and c,d > 0. All intermediate states must remain positive. ll positiveCore(ll a, ll b, ll c, ll d) { ll answer = 0; while (true) { if (c < a || d < b) return -1; if (a == c && b == d) return answer; if (c == d) return -1; if (c < d) { swap(a, b); swap(c, d); continue; } // Now c > d. The last reverse operations are forced to be c -= d. if (d == b && (c - a) % d == 0) { return answer + (c - a) / d; } // Reduce c to a value in [1,d], unless this would overshoot a. ll steps = (c - 1) / d; ll maximumSteps = (c - a) / d; if (steps > maximumSteps) return -1; c -= steps * d; answer += steps; } } // Nonnegative initial state, with a nonnegative target. ll nonnegative(ll a, ll b, ll c, ll d) { if (c < a || d < b) return -1; if (a == c && b == d) return 0; if (a == 0 && b == 0) return -1; if (a == 0) { // To make the first coordinate nonzero, (0,b) -> (b,b) is forced. if (c == 0) return -1; ll result = positiveCore(b, b, c, d); return result < 0 ? -1 : result + 1; } if (b == 0) { if (d == 0) return -1; ll result = positiveCore(a, a, c, d); return result < 0 ? -1 : result + 1; } return positiveCore(a, b, c, d); } struct FSeg { ll x, y; // Candidates are z = x-k*y, second coordinate z-y. ll maxK; ll prefix; ll minZ, maxZ; }; struct BSeg { ll u, v; // Candidates are (u-t*v,v). ll maxT; ll prefix; ll minZ, maxZ; }; // Candidates for crossing from (x,-y), x>y, to the positive pair (x,x-y). vector<FSeg> buildForwardSegments(ll A, ll B) { vector<FSeg> segments; segments.reserve(128); ll x = A, y = B, prefix = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; ll maxK = r ? q - 1 : q - 2; if (maxK >= 0) { ll minZ = x - maxK * y; segments.push_back({x, y, maxK, prefix, minZ, x}); } if (r) { prefix += q; x = r; } else { break; } } else { ll q = y / x; ll r = y % x; if (r) { prefix += q; y = r; } else { break; } } } return segments; } // Positive ancestors of the target which can serve as a crossing state. vector<BSeg> buildBackwardSegments(ll C, ll D) { vector<BSeg> segments; segments.reserve(128); ll x = C, y = D, prefix = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; ll maxT = r ? q - 1 : q - 2; if (maxT >= 0) { ll minZ = x - maxT * y; segments.push_back({x, y, maxT, prefix, minZ, x}); } if (r) { prefix += q; x = r; } else { break; } } else { ll q = y / x; ll r = y % x; if (r) { prefix += q; y = r; } else { break; } } } return segments; } // Reach (g,-g), where g = gcd(A,B), using only sign-preserving operations. pair<ll, ll> equalStateInfo(ll A, ll B) { ll x = A, y = B, distance = 0; while (x != y) { if (x > y) { ll q = x / y; ll r = x % y; if (r) { distance += q; x = r; } else { distance += q - 1; x = y; } } else { ll q = y / x; ll r = y % x; if (r) { distance += q; y = r; } else { distance += q - 1; y = x; } } } return {x, distance}; } // Target is still in the quadrant (positive,negative). ll oppositeDistance(ll A, ll B, ll C, ll D) { ll x = A, y = B, prefix = 0; while (true) { if (x == C && y == D) return prefix; if (x == y) return -1; if (x > y) { ll q = x / y; ll r = x % y; ll steps = r ? q : q - 1; ll endX = r ? r : y; if (D == y && C <= x && C >= endX && (x - C) % y == 0) { ll k = (x - C) / y; if (k <= steps) return prefix + k; } prefix += steps; x = endX; } else { ll q = y / x; ll r = y % x; ll steps = r ? q : q - 1; ll endY = r ? r : x; if (C == x && D <= y && D >= endY && (y - D) % x == 0) { ll k = (y - D) / x; if (k <= steps) return prefix + k; } prefix += steps; y = endY; } } } // Start is (A,-B), A,B>0; target is strictly positive. ll crossToPositive(ll A, ll B, ll C, ll D) { ll best = INF; // Route through (g,-g), then (g,0), followed by nonnegative operations. auto [g, toEqual] = equalStateInfo(A, B); ll viaZero = nonnegative(g, 0, C, D); if (viaZero >= 0) { best = toEqual + 1 + viaZero; } vector<FSeg> forward = buildForwardSegments(A, B); vector<BSeg> backward = buildBackwardSegments(C, D); // Both lists consist of disjoint intervals, ordered by decreasing z. size_t i = 0, j = 0; while (i < forward.size() && j < backward.size()) { const FSeg &f = forward[i]; const BSeg &b = backward[j]; if (f.minZ > b.maxZ) { ++i; continue; } if (b.minZ > f.maxZ) { ++j; continue; } // Equality of second coordinates gives z-y = v, hence z = y+v. ll z = f.y + b.v; if (z >= f.minZ && z <= f.maxZ && z >= b.minZ && z <= b.maxZ && (f.x - z) % f.y == 0 && (b.u - z) % b.v == 0) { ll k = (f.x - z) / f.y; ll t = (b.u - z) / b.v; ll total = f.prefix + k + 1 + b.prefix + t; best = min(best, total); } if (f.minZ > b.minZ) { ++i; } else if (f.minZ < b.minZ) { ++j; } else { ++i; ++j; } } return best == INF ? -1 : best; } ll solveQuery(ll a, ll b, ll c, ll d) { if (a == 0 && b == 0) { return (c == 0 && d == 0) ? 0 : -1; } if (a >= 0 && b >= 0) { if (c < 0 || d < 0) return -1; return nonnegative(a, b, c, d); } if (a <= 0 && b <= 0) { if (c > 0 || d > 0) return -1; return nonnegative(-a, -b, -c, -d); } // Normalize the opposite-sign start to a>0, b<0. if (a < 0) { swap(a, b); swap(c, d); } ll A = a; ll B = -b; if (c > 0 && d < 0) { return oppositeDistance(A, B, c, -d); } if (c < 0 && d > 0) { return -1; } if (c > 0 && d > 0) { return crossToPositive(A, B, c, d); } if (c < 0 && d < 0) { // Negate everything and swap coordinates. return crossToPositive(B, A, -d, -c); } // A target with a zero coordinate can only be reached immediately after // arriving at (g,-g). auto [g, toEqual] = equalStateInfo(A, B); if ((c == g && d == 0) || (c == 0 && d == -g)) { return toEqual + 1; } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { ll a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; using i128 = __int128_t; struct Run { int64 x, y; // First pair in this run int64 start; // Global index of the first pair int64 n; // Number of pairs in the run int64 lo, hi; // Depth interval of these pairs bool horizontal; // x > y }; struct RunInfo { vector<Run> runs; int64 depth = 0; int64 root = 0; }; static int64 abs64(int64 x) { return x < 0 ? -x : x; } // Compressed list of all non-root ancestors of (x,y), including (x,y). // A run with x>y contains (x-t*y,y); one with y>x contains (x,y-t*x). static RunInfo buildRuns(int64 x, int64 y) { RunInfo info; int64 index = 0; while (x != y) { Run r; r.x = x; r.y = y; r.start = index; r.horizontal = (x > y); if (x > y) { int64 q = x / y; r.n = (x % y == 0 ? q - 1 : q); x -= r.n * y; } else { int64 q = y / x; r.n = (y % x == 0 ? q - 1 : q); y -= r.n * x; } index += r.n; info.runs.push_back(r); } info.depth = index; info.root = x; // x == y == gcd of the original pair for (Run &r : info.runs) { r.hi = info.depth - r.start; r.lo = r.hi - r.n + 1; } return info; } // Number of parent steps from the pair used to build info to anc, // or -1 if anc is not an ancestor. static int64 ancestorDist(const RunInfo &info, pair<int64,int64> anc) { for (const Run &r : info.runs) { if (r.horizontal) { if (anc.second == r.y && anc.first > r.y && anc.first <= r.x) { int64 diff = r.x - anc.first; if (diff % r.y == 0) { int64 t = diff / r.y; if (t < r.n) return r.start + t; } } } else { if (anc.first == r.x && anc.second > r.x && anc.second <= r.y) { int64 diff = r.y - anc.second; if (diff % r.x == 0) { int64 t = diff / r.x; if (t < r.n) return r.start + t; } } } } if (anc.first == info.root && anc.second == info.root) return info.depth; return -1; } static int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { // Zero initial states: one useful operation reaches (s,s), after which // the ordinary same-sign process applies. if (a == 0 || b == 0) { if (a == 0 && b == 0) return (c == 0 && d == 0) ? 0 : -1; if (a == c && b == d) return 0; int64 s = (b == 0 ? a : b); bool correctSign = (s > 0 && c > 0 && d > 0) || (s < 0 && c < 0 && d < 0); if (!correctSign) return -1; int64 x = abs64(c), y = abs64(d); if (std::gcd(x, y) != abs64(s)) return -1; RunInfo target = buildRuns(x, y); return target.depth + 1; } // Both initial components have the same sign. if ((a > 0 && b > 0) || (a < 0 && b < 0)) { bool correctSign = (a > 0 && c > 0 && d > 0) || (a < 0 && c < 0 && d < 0); if (!correctSign) return -1; pair<int64,int64> start = {abs64(a), abs64(b)}; pair<int64,int64> target = {abs64(c), abs64(d)}; RunInfo info = buildRuns(target.first, target.second); return ancestorDist(info, start); } // Canonicalize an opposite-sign start to a>0>b. Swapping both pairs // preserves operation counts. if (a < 0) { swap(a, b); swap(c, d); } int64 x = a, y = -b; RunInfo startInfo = buildRuns(x, y); int64 g = startInfo.root; // Zero targets are reachable only through (g,-g). if (c == 0 || d == 0) { if ((c == 0 && d == -g) || (c == g && d == 0)) return startInfo.depth + 1; return -1; } // Still opposite signs: only the deterministic non-crossing chain applies. if (c > 0 && d < 0) { return ancestorDist(startInfo, {c, -d}); } if (c < 0 && d > 0) return -1; // The target has equal signs. Normalize to positive absolute values. bool positiveTarget = (c > 0); int64 tx = abs64(c), ty = abs64(d); if (std::gcd(tx, ty) != g) return -1; RunInfo targetInfo = buildRuns(tx, ty); // Fallback: go to (g,-g), then through a zero state to (g,g) or (-g,-g), // and finally follow the same-sign path to the target. i128 best = (i128)startInfo.depth + targetInfo.depth + 2; // A crossing at a non-root ancestor (x,y), x>y, produces the positive // base (x,x-y). At x<y it produces the negative base with absolute // values (y-x,y). Match all such bases against ancestors of the target. const auto &S = startInfo.runs; const auto &T = targetInfo.runs; size_t i = 0, j = 0; while (i < S.size() && j < T.size()) { const Run &s = S[i]; const Run &t = T[j]; bool overlap = !(s.hi < t.lo || t.hi < s.lo); if (!overlap) { if (s.lo > t.hi) ++i; else ++j; continue; } // Positive bases come from horizontal runs, negative ones from // vertical runs. Equal pairs must also have the same orientation. if (s.horizontal == positiveTarget && s.horizontal == t.horizontal) { if (s.horizontal) { // Base: (s.x-k*s.y, s.x-(k+1)*s.y) // Target run: (t.x-l*t.y, t.y) int64 diff = s.x - t.y; if (diff > 0 && diff % s.y == 0) { int64 h = diff / s.y; // h = k+1 if (h >= 1 && h <= s.n) { int64 k = h - 1; int64 baseX = s.x - k * s.y; int64 diff2 = t.x - baseX; if (diff2 >= 0 && diff2 % t.y == 0) { int64 l = diff2 / t.y; if (l < t.n) { i128 cost = (i128)s.start + k + 1 + t.start + l; if (cost < best) best = cost; } } } } } else { // Base: (s.y-(k+1)*s.x, s.y-k*s.x) // Target run: (t.x, t.y-l*t.x) int64 diff = s.y - t.x; if (diff > 0 && diff % s.x == 0) { int64 h = diff / s.x; // h = k+1 if (h >= 1 && h <= s.n) { int64 k = h - 1; int64 baseY = s.y - k * s.x; int64 diff2 = t.y - baseY; if (diff2 >= 0 && diff2 % t.x == 0) { int64 l = diff2 / t.x; if (l < t.n) { i128 cost = (i128)s.start + k + 1 + t.start + l; if (cost < best) best = cost; } } } } } } // Enumerate only pairs of runs whose depth intervals overlap. if (s.lo > t.lo) ++i; else if (t.lo > s.lo) ++j; else { ++i; ++j; } } return (int64)best; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; long long gcdll(long long a, long long b) { if (a < 0) a = -a; if (b < 0) b = -b; while (b) { long long t = a % b; a = b; b = t; } return a; } // Depth of a positive primitive pair (x, y) in the Stern-Brocot tree // rooted at (1, 1), using reverse subtraction. long long depth_positive(long long x, long long y) { long long d = 0; while (!(x == 1 && y == 1)) { if (x > y) { long long q = (x - 1) / y; x -= q * y; d += q; } else { long long q = (y - 1) / x; y -= q * x; d += q; } } return d; } // Move (x, y) up by 'steps' parent operations in the positive tree. pair<long long, long long> climb(long long x, long long y, long long steps) { while (steps > 0 && !(x == 1 && y == 1)) { if (x > y) { long long q = (x - 1) / y; long long take = min(q, steps); x -= take * y; steps -= take; } else { long long q = (y - 1) / x; long long take = min(q, steps); y -= take * x; steps -= take; } } return {x, y}; } // Minimum operations from positive primitive (x,y) to positive primitive (c,d). long long positive_distance(long long x, long long y, long long c, long long d) { long long ds = depth_positive(x, y); long long dt = depth_positive(c, d); if (ds > dt) return -1; auto anc = climb(c, d, dt - ds); if (anc.first == x && anc.second == y) return dt - ds; return -1; } // Source is PN: (p, -q), target is PN: (r, -s), all p,q,r,s > 0. long long mixed_same(long long p, long long q, long long r, long long s) { long long ds = depth_positive(p, q); long long dt = depth_positive(r, s); if (dt > ds) return -1; auto anc = climb(p, q, ds - dt); if (anc.first == r && anc.second == s) return ds - dt; return -1; } struct Seg { long long l, r; long long x0, y0; long long sx, sy; }; struct Path { vector<Seg> segs; long long depth; }; // Build root-to-(X,Y) path in the positive primitive tree. // X,Y > 0 and gcd(X,Y)=1. Path build_path(long long X, long long Y) { vector<pair<char, long long>> rev; long long x = X, y = Y; while (!(x == 1 && y == 1)) { if (x > y) { long long q = (x - 1) / y; rev.push_back({'A', q}); x -= q * y; } else { long long q = (y - 1) / x; rev.push_back({'B', q}); y -= q * x; } } reverse(rev.begin(), rev.end()); Path path; path.segs.push_back({0, 0, 1, 1, 0, 0}); long long curx = 1, cury = 1, dep = 0; for (auto [op, q] : rev) { long long l = dep + 1; long long r = dep + q; if (op == 'A') { path.segs.push_back({l, r, curx + cury, cury, cury, 0}); curx += q * cury; } else { path.segs.push_back({l, r, curx, cury + curx, 0, curx}); cury += q * curx; } dep = r; } path.depth = dep; return path; } // Source is PN: (p, -q). Target is PP: (c, d). // All p,q,c,d > 0. long long calc(long long p, long long q, long long c, long long d) { Path ps = build_path(p, q); Path pt = build_path(c, d); long long DS = ps.depth; long long DC = pt.depth; long long limit = min(DS, DC); long long best = -1; size_t i = 0, j = 0; while (i < ps.segs.size() && j < pt.segs.size()) { long long L = max(ps.segs[i].l, pt.segs[j].l); long long R = min(ps.segs[i].r, pt.segs[j].r); if (L <= R) { long long LL = max(L, 1LL); long long RR = min(R, limit); if (LL <= RR) { const Seg &ss = ps.segs[i]; const Seg &tt = pt.segs[j]; __int128 Sx = (__int128)ss.x0 + (__int128)ss.sx * (LL - ss.l); __int128 Sy = (__int128)ss.y0 + (__int128)ss.sy * (LL - ss.l); __int128 Cx = (__int128)tt.x0 + (__int128)tt.sx * (LL - tt.l); __int128 Cy = (__int128)tt.y0 + (__int128)tt.sy * (LL - tt.l); __int128 sx = ss.sx, sy = ss.sy; __int128 tx = tt.sx, ty = tt.sy; // Need: // Sx(t) = Cx(t) // Sx(t) - Sy(t) = Cy(t) // // t = LL + k __int128 a1 = sx - tx; __int128 b1 = Cx - Sx; __int128 a2 = sx - sy - ty; __int128 b2 = Cy - (Sx - Sy); long long len = RR - LL; long long cand = -1; if (a1 == 0) { if (b1 == 0) { if (a2 == 0) { if (b2 == 0) cand = RR; } else { if (b2 % a2 == 0) { __int128 k = b2 / a2; if (k >= 0 && k <= len) { cand = LL + (long long)k; } } } } } else { if (b1 % a1 == 0) { __int128 k = b1 / a1; if (k >= 0 && k <= len) { if (a2 * k == b2) { cand = LL + (long long)k; } } } } if (cand > best) best = cand; } } if (ps.segs[i].r < pt.segs[j].r) { ++i; } else if (ps.segs[i].r > pt.segs[j].r) { ++j; } else { ++i; ++j; } } if (best != -1) { return DS + DC + 1 - 2LL * best; } else { // Go through (1,0): mixed -> zero -> (1,1) -> target. return DS + DC + 2; } } long long solve_query(long long a, long long b, long long c, long long d) { long long g1 = gcdll(a, b); if (g1 == 0) { return (c == 0 && d == 0) ? 0 : -1; } long long g2 = gcdll(c, d); if (g1 != g2) return -1; a /= g1; b /= g1; c /= g1; d /= g1; // Source positive-positive. if (a > 0 && b > 0) { if (c > 0 && d > 0) return positive_distance(a, b, c, d); return -1; } // Source negative-negative. if (a < 0 && b < 0) { if (c < 0 && d < 0) return positive_distance(-a, -b, -c, -d); return -1; } // Source has a zero coordinate. if (a == 0 || b == 0) { if (a == 1 && b == 0) { if (c == 1 && d == 0) return 0; if (c > 0 && d > 0) return 1 + depth_positive(c, d); return -1; } if (a == -1 && b == 0) { if (c == -1 && d == 0) return 0; if (c < 0 && d < 0) return 1 + depth_positive(-c, -d); return -1; } if (a == 0 && b == 1) { if (c == 0 && d == 1) return 0; if (c > 0 && d > 0) return 1 + depth_positive(c, d); return -1; } if (a == 0 && b == -1) { if (c == 0 && d == -1) return 0; if (c < 0 && d < 0) return 1 + depth_positive(-c, -d); return -1; } return -1; } // Now source is mixed. If it is NP, swap coordinates to make it PN. if (a < 0 && b > 0) { swap(a, b); swap(c, d); } // Source is PN: (a,b) = (p, -q). long long p = a; long long q = -b; // Target PN. if (c > 0 && d < 0) { return mixed_same(p, q, c, -d); } // Target NP: impossible because mixed sign pattern cannot flip. if (c < 0 && d > 0) { return -1; } // Target PP. if (c > 0 && d > 0) { return calc(p, q, c, d); } // Target NN. if (c < 0 && d < 0) { return calc(q, p, -d, -c); } // Target has a zero coordinate. if ((c == 1 && d == 0) || (c == 0 && d == -1)) { return depth_positive(p, q) + 1; } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { long long a, b, c, d; cin >> a >> b >> c >> d; cout << solve_query(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using ll = long long; ll gcd_abs(ll x, ll y) { if (x < 0) x = -x; if (y < 0) y = -y; while (y) { ll t = x % y; x = y; y = t; } return x; } // Number of subtractive Euclidean steps from (x, y) to (g, g), x,y > 0. ll depth_positive(ll x, ll y) { ll dep = 0; while (x != y) { if (x > y) { ll q = (x - 1) / y; dep += q; x -= q * y; } else { ll q = (y - 1) / x; dep += q; y -= q * x; } } return dep; } // Ancestor of (x,y) after moving k steps towards the root (g,g). pair<ll,ll> ancestor_at_depth(ll x, ll y, ll k) { while (k > 0 && x != y) { if (x > y) { ll q = (x - 1) / y; ll take = min(k, q); x -= take * y; k -= take; } else { ll q = (y - 1) / x; ll take = min(k, q); y -= take * x; k -= take; } } return {x, y}; } // Minimum operations from positive (x1,y1) to positive (x2,y2), // where operations are only increasing positive pairs. ll dist_positive(ll x1, ll y1, ll x2, ll y2) { if (x1 == x2 && y1 == y2) return 0; ll d1 = depth_positive(x1, y1); ll d2 = depth_positive(x2, y2); if (d1 > d2) return -1; auto p = ancestor_at_depth(x2, y2, d2 - d1); if (p.first == x1 && p.second == y1) return d2 - d1; return -1; } // Find k in [0, L] such that F(A(k)) = B(k), where A starts as (ax, ay), // B starts as (bx, by), and A(k), B(k) are obtained by k parent steps. // F(u,v) = (u, u-v), only for u > v. bool solve_interval(ll ax, ll ay, ll bx, ll by, ll L, ll &kout) { bool axGreater = (ax > ay); ll P01, P02, Ps1, Ps2; if (axGreater) { // A(k) = (ax - k*ay, ay) // F(A(k)) = (ax - k*ay, ax - (k+1)*ay) P01 = ax; P02 = ax - ay; Ps1 = -ay; Ps2 = -ay; } else { // A(k) = (ax, ay - k*ax) // F(A(k)) = (ax, ax - ay + k*ax) P01 = ax; P02 = ax - ay; Ps1 = 0; Ps2 = ax; } bool bxGreater = (bx > by); ll B01, B02, Bs1, Bs2; if (bxGreater) { B01 = bx; B02 = by; Bs1 = -by; Bs2 = 0; } else { B01 = bx; B02 = by; Bs1 = 0; Bs2 = -bx; } ll C1 = P01 - B01; ll D1 = Bs1 - Ps1; ll C2 = P02 - B02; ll D2 = Bs2 - Ps2; auto checkK = [&](ll k) -> bool { if (k < 0 || k > L) return false; ll u, v; if (axGreater) { u = ax - k * ay; v = ay; } else { u = ax; v = ay - k * ax; } if (u <= v) return false; ll b1, b2; if (bxGreater) { b1 = bx - k * by; b2 = by; } else { b1 = bx; b2 = by - k * bx; } return (u == b1 && (u - v) == b2); }; if (D1 == 0 && D2 == 0) { if (C1 != 0 || C2 != 0) return false; ll k = 0; if (!axGreater) { k = (ay - ax) / ax + 1; } if (k <= L && checkK(k)) { kout = k; return true; } return false; } if (D1 != 0) { if (C1 % D1 == 0) { ll k = C1 / D1; if (k >= 0 && k <= L && (__int128)k * D1 == C1) { if ((__int128)k * D2 == C2 && checkK(k)) { kout = k; return true; } } } return false; } else { if (C1 != 0) return false; if (D2 != 0 && C2 % D2 == 0) { ll k = C2 / D2; if (k >= 0 && k <= L && (__int128)k * D2 == C2 && checkK(k)) { kout = k; return true; } } return false; } } // Start is signed (sx, -sy), sx,sy > 0. // Target is positive (tx,ty), tx,ty > 0. ll solve_positive_target(ll sx, ll sy, ll tx, ll ty) { ll ds = depth_positive(sx, sy); ll dt = depth_positive(tx, ty); ll m = min(ds, dt); auto A = ancestor_at_depth(sx, sy, ds - m); auto B = ancestor_at_depth(tx, ty, dt - m); ll cur = m; while (cur > 0) { ll ax = A.first, ay = A.second; ll bx = B.first, by = B.second; ll la, lb; if (ax > ay) la = (ax - 1) / ay; else la = (ay - 1) / ax; if (bx > by) lb = (bx - 1) / by; else lb = (by - 1) / bx; ll L = min(la, lb); L = min(L, cur); ll k; if (solve_interval(ax, ay, bx, by, L, k)) { ll d = cur - k; if (d > 0) { return ds + dt + 1 - 2 * d; } } if (ax > ay) A.first = ax - L * ay; else A.second = ay - L * ax; if (bx > by) B.first = bx - L * by; else B.second = by - L * bx; cur -= L; } // Cross at the equality (g,-g) -> (g,0) -> (g,g). return ds + dt + 2; } // Start and target are both nonnegative. ll solve_same_positive(ll a, ll b, ll c, ll d) { if (a == 0 && b == 0) { return (c == 0 && d == 0) ? 0 : -1; } if (a == 0) { ll val = b; if (c == 0 && d == val) return 0; if (c > 0 && d > 0) { ll extra = dist_positive(val, val, c, d); if (extra == -1) return -1; return 1 + extra; } return -1; } if (b == 0) { ll val = a; if (c == val && d == 0) return 0; if (c > 0 && d > 0) { ll extra = dist_positive(val, val, c, d); if (extra == -1) return -1; return 1 + extra; } return -1; } if (c <= 0 || d <= 0) return -1; return dist_positive(a, b, c, d); } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { ll a, b, c, d; cin >> a >> b >> c >> d; if (a == 0 && b == 0) { cout << ((c == 0 && d == 0) ? 0 : -1) << '\n'; continue; } ll gs = gcd_abs(a, b); ll gt = gcd_abs(c, d); if (gs != gt) { cout << -1 << '\n'; continue; } bool opposite = ((a < 0 && b > 0) || (a > 0 && b < 0)); if (opposite) { if (a < 0 && b > 0) { swap(a, b); swap(c, d); } // Now a > 0, b < 0. ll A = a; ll B = -b; ll ans; if (c > 0 && d < 0) { // Opposite signs, same orientation. ll C = c; ll D = -d; ans = dist_positive(C, D, A, B); } else if (c < 0 && d > 0) { // Opposite signs, swapped orientation: impossible. ans = -1; } else if (c > 0 && d > 0) { // Positive target. ans = solve_positive_target(A, B, c, d); } else if (c < 0 && d < 0) { // Negative target: negate + swap, then positive target. ll C = -c; ll D = -d; ans = solve_positive_target(B, A, D, C); } else { // Target has a zero coordinate. ll ds = depth_positive(A, B); if (c == gs && d == 0) { ans = ds + 1; } else if (c == 0 && d == -gs) { ans = ds + 1; } else { ans = -1; } } cout << ans << '\n'; } else { // Same sign or contains zero. // Normalize non-positive start to nonnegative. if (a < 0 || b < 0) { a = -a; b = -b; c = -c; d = -d; } if (c < 0 || d < 0) { cout << -1 << '\n'; continue; } ll ans = solve_same_positive(a, b, c, d); cout << ans << '\n'; } } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; using i128 = __int128_t; const i128 INF = ((i128)1 << 125); long long gcdll(long long a, long long b) { if (a < 0) a = -a; if (b < 0) b = -b; while (b) { long long t = a % b; a = b; b = t; } return a; } // returns x, y such that a*x + b*y = gcd(|a|, |b|) pair<i128, i128> bezout(long long a, long long b) { long long A = (a < 0 ? -a : a); long long B = (b < 0 ? -b : b); i128 old_r = A, r = B; i128 old_s = 1, s = 0; i128 old_t = 0, t = 1; while (r != 0) { i128 q = old_r / r; i128 nr = old_r - q * r; i128 ns = old_s - q * s; i128 nt = old_t - q * t; old_r = r; r = nr; old_s = s; s = ns; old_t = t; t = nt; } i128 x = old_s; i128 y = old_t; if (a < 0) x = -x; if (b < 0) y = -y; return {x, y}; } i128 ceil_div(i128 a, i128 b) { // b > 0, returns ceil(a / b) if (a >= 0) return (a + b - 1) / b; return -((-a) / b); } i128 floor_div(i128 a, i128 b) { // b > 0, returns floor(a / b) if (a >= 0) return a / b; return -((-a + b - 1) / b); } i128 matrix_length(i128 p, i128 q, i128 r, i128 s) { // M = [[p, q], [r, s]] i128 ans = 0; while (!(p == 1 && q == 0 && r == 0 && s == 1)) { if (q >= p && s >= r) { // subtract first column from second column i128 k = INF; if (p > 0) k = min(k, q / p); if (r > 0) k = min(k, s / r); ans += k; q -= k * p; s -= k * r; } else { // subtract second column from first column i128 k = INF; if (q > 0) k = min(k, p / q); if (s > 0) k = min(k, r / s); ans += k; p -= k * q; r -= k * s; } } return ans; } i128 solve_query(long long a, long long b, long long c, long long d) { // gcd(a,b)=gcd(c,d)=1 here, and not both zero auto [u, v0] = bezout(a, b); // a*u + b*v0 = 1 auto [P, Q] = bezout(d, c); // d*P + c*Q = 1 i128 T00 = P; i128 T01 = -Q; i128 X0[2], Y0[2]; X0[0] = (i128)u * c + (i128)b * T00; X0[1] = (i128)u * d + (i128)b * T01; Y0[0] = (i128)v0 * c - (i128)a * T00; Y0[1] = (i128)v0 * d - (i128)a * T01; i128 L = -INF, U = INF; bool ok = true; auto add_ineq = [&](i128 val, i128 coeff) { // val + coeff * k >= 0 if (coeff == 0) { if (val < 0) ok = false; } else if (coeff > 0) { i128 need = ceil_div(-val, coeff); if (need > L) L = need; } else { i128 pos = -coeff; i128 bound = floor_div(val, pos); if (bound < U) U = bound; } }; add_ineq(X0[0], (i128)b * c); add_ineq(X0[1], (i128)b * d); add_ineq(Y0[0], -(i128)a * c); add_ineq(Y0[1], -(i128)a * d); if (!ok || L > U) return -1; auto eval = [&](i128 k) -> i128 { i128 p = X0[0] + (i128)b * c * k; i128 r = X0[1] + (i128)b * d * k; i128 q = Y0[0] - (i128)a * c * k; i128 s = Y0[1] - (i128)a * d * k; return matrix_length(p, q, r, s); }; i128 best = -1; if (L > -INF / 2) { best = eval(L); } if (U < INF / 2) { i128 cur = eval(U); if (best == -1 || cur < best) best = cur; } if (best == -1) { // both bounds are infinite; should almost never happen best = eval(0); } return best; } void print_i128(i128 x) { if (x == 0) { cout << 0 << '\n'; return; } if (x < 0) { cout << '-'; x = -x; } string s; while (x > 0) { s.push_back(char('0' + (int)(x % 10))); x /= 10; } reverse(s.begin(), s.end()); cout << s << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { long long a, b, c, d; cin >> a >> b >> c >> d; long long g1 = gcdll(a, b); long long g2 = gcdll(c, d); if (g1 != g2) { cout << -1 << '\n'; continue; } if (g1 == 0) { cout << 0 << '\n'; continue; } a /= g1; b /= g1; c /= g1; d /= g1; if (a == c && b == d) { cout << 0 << '\n'; continue; } i128 ans = solve_query(a, b, c, d); print_i128(ans); } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; struct Run { char ch; int64 cnt; }; struct Word { vector<Run> runs; int64 len = 0; }; int64 abs64(int64 x) { return x < 0 ? -x : x; } /* For a positive coprime pair (x,y), construct the word of operations from (1,1) to (x,y), in run-length encoded form. 'A' means a += b. 'B' means b += a. */ Word makeWord(int64 x, int64 y) { vector<Run> reversedRuns; reversedRuns.reserve(96); int64 length = 0; while (x != y) { if (x > y) { int64 k = (x - 1) / y; reversedRuns.push_back({'A', k}); x -= k * y; length += k; } else { int64 k = (y - 1) / x; reversedRuns.push_back({'B', k}); y -= k * x; length += k; } } Word result; result.len = length; result.runs.reserve(reversedRuns.size()); for (auto it = reversedRuns.rbegin(); it != reversedRuns.rend(); ++it) { result.runs.push_back(*it); } return result; } /* Returns whether the first word is a prefix of the second word. */ bool isPrefix(const Word& small, const Word& large) { if (small.runs.empty()) return true; if (large.runs.empty()) return false; size_t i = 0, j = 0; int64 remSmall = small.runs[0].cnt; int64 remLarge = large.runs[0].cnt; while (i < small.runs.size()) { if (j >= large.runs.size()) return false; if (small.runs[i].ch != large.runs[j].ch) { return false; } int64 take = min(remSmall, remLarge); remSmall -= take; remLarge -= take; if (remSmall == 0) { ++i; if (i < small.runs.size()) { remSmall = small.runs[i].cnt; } } if (remLarge == 0) { ++j; if (j < large.runs.size()) { remLarge = large.runs[j].cnt; } } } return true; } /* Finds the first position at which the two words contain the same letter. The letters at all earlier positions are different. */ int64 firstEqual(const Word& a, const Word& b, char& common) { if (a.runs.empty() || b.runs.empty()) { common = '\0'; return -1; } size_t i = 0, j = 0; int64 remA = a.runs[0].cnt; int64 remB = b.runs[0].cnt; int64 pos = 0; while (i < a.runs.size() && j < b.runs.size()) { if (a.runs[i].ch == b.runs[j].ch) { common = a.runs[i].ch; return pos; } int64 take = min(remA, remB); pos += take; remA -= take; remB -= take; if (remA == 0) { ++i; if (i < a.runs.size()) remA = a.runs[i].cnt; } if (remB == 0) { ++j; if (j < b.runs.size()) remB = b.runs[j].cnt; } } common = '\0'; return -1; } int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { if (a == 0 && b == 0) { return (c == 0 && d == 0) ? 0 : -1; } int64 g1 = gcd(abs64(a), abs64(b)); int64 g2 = gcd(abs64(c), abs64(d)); if (g1 != g2) return -1; // Operations commute with scaling, so normalize the gcd to 1. a /= g1; b /= g1; c /= g1; d /= g1; /* Source has a zero coordinate. Canonicalize it to (1,0). Swapping coordinates and negating both coordinates preserve the minimum number of operations. */ if (a == 0 || b == 0) { if (a == 0) { swap(a, b); swap(c, d); } if (a < 0) { a = -a; b = -b; c = -c; d = -d; } // The source is now (1,0). if (c == 1 && d == 0) return 0; if (c > 0 && d > 0) { // (1,0) -> (1,1), then follow the positive tree. return 1 + makeWord(c, d).len; } return -1; } // Both source coordinates have the same sign. if ((a > 0) == (b > 0)) { if (a < 0) { if (!(c < 0 && d < 0)) return -1; a = -a; b = -b; c = -c; d = -d; } else { if (!(c > 0 && d > 0)) return -1; } Word sourceWord = makeWord(a, b); Word targetWord = makeWord(c, d); if (!isPrefix(sourceWord, targetWord)) return -1; return targetWord.len - sourceWord.len; } // The source has opposite signs. bool sourceFirstPositive = (a > 0); // Target has two coordinates of the same sign. if ((c > 0 && d > 0) || (c < 0 && d < 0)) { if (c < 0) { a = -a; b = -b; c = -c; d = -d; } // Canonicalize the mixed source to (x,-y). if (a < 0) { swap(a, b); swap(c, d); } Word sourceWord = makeWord(a, -b); Word targetWord = makeWord(c, d); char common; int64 k = firstEqual(sourceWord, targetWord, common); if (k >= 0 && common == 'A') { // A direct crossing from the mixed region into the positive region. return sourceWord.len + targetWord.len - 2 * k - 1; } /* Otherwise, the unique route to the positive region is: (1,-1) -> (1,0) -> (1,1), after exhausting the mixed chain. */ return sourceWord.len + 2 + targetWord.len; } // Target has exactly one zero coordinate. if (c == 0 || d == 0) { int64 mixedLength = makeWord(abs64(a), abs64(b)).len; if (sourceFirstPositive) { // From (1,-1), both (1,0) and (0,-1) are reachable. if ((c == 1 && d == 0) || (c == 0 && d == -1)) { return mixedLength + 1; } } else { // From (-1,1), both (-1,0) and (0,1) are reachable. if ((c == -1 && d == 0) || (c == 0 && d == 1)) { return mixedLength + 1; } } return -1; } // Both source and target have mixed signs. bool targetFirstPositive = (c > 0); if (sourceFirstPositive != targetFirstPositive) return -1; // Canonicalize both mixed pairs to the (+,-) quadrant. if (!sourceFirstPositive) { swap(a, b); swap(c, d); } Word sourceWord = makeWord(a, -b); Word targetWord = makeWord(c, -d); if (!isPrefix(targetWord, sourceWord)) return -1; return sourceWord.len - targetWord.len; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; enum Kind { ZERO_KIND, AXIS_KIND, POSITIVE_KIND, NEGATIVE_KIND, MIXED_KIND }; int64 magnitude(int64 x) { return x < 0 ? -x : x; } int64 gcd64(int64 x, int64 y) { return std::gcd(x, y); } Kind classify(int64 x, int64 y) { if (x == 0 && y == 0) return ZERO_KIND; if (x == 0 || y == 0) return AXIS_KIND; if (x > 0 && y > 0) return POSITIVE_KIND; if (x < 0 && y < 0) return NEGATIVE_KIND; return MIXED_KIND; } struct Block { char op; int64 count; }; struct Path { vector<Block> blocks; int64 length = 0; char charAt(int64 index) const { for (const Block &b : blocks) { if (index < b.count) return b.op; index -= b.count; } return '?'; } }; /* For positive x and y, consider the tree rooted at (gcd(x,y), gcd(x,y)). An 'A' edge means (x,y) -> (x+y,y). A 'B' edge means (x,y) -> (x,x+y). The parent of (x,y) is obtained by subtracting the smaller coordinate from the larger one. Build the root-to-node path as run-length encoded blocks without expanding potentially enormous runs. */ Path buildPath(int64 x, int64 y) { vector<Block> reversed; reversed.reserve(96); while (x != y) { if (x > y) { int64 count = (x - 1) / y; reversed.push_back({'A', count}); x -= count * y; } else { int64 count = (y - 1) / x; reversed.push_back({'B', count}); y -= count * x; } } Path result; result.blocks.reserve(reversed.size()); for (auto it = reversed.rbegin(); it != reversed.rend(); ++it) { result.blocks.push_back(*it); result.length += it->count; } return result; } // Returns whether a is a prefix of b. bool isPrefix(const Path &a, const Path &b) { size_t i = 0, j = 0; int64 remA = a.blocks.empty() ? 0 : a.blocks[0].count; int64 remB = b.blocks.empty() ? 0 : b.blocks[0].count; while (i < a.blocks.size()) { if (j == b.blocks.size()) return false; if (a.blocks[i].op != b.blocks[j].op) return false; int64 take = min(remA, remB); remA -= take; remB -= take; if (remA == 0) { ++i; if (i < a.blocks.size()) remA = a.blocks[i].count; } if (remB == 0) { ++j; if (j < b.blocks.size()) remB = b.blocks[j].count; } } return true; } // LCP of a and b, after exchanging 'A' and 'B' in a. int64 lcpMirrored(const Path &a, const Path &b) { size_t i = 0, j = 0; int64 remA = a.blocks.empty() ? 0 : a.blocks[0].count; int64 remB = b.blocks.empty() ? 0 : b.blocks[0].count; int64 answer = 0; while (i < a.blocks.size() && j < b.blocks.size()) { char ca = a.blocks[i].op; ca = (ca == 'A' ? 'B' : 'A'); if (ca != b.blocks[j].op) break; int64 take = min(remA, remB); answer += take; remA -= take; remB -= take; if (remA == 0) { ++i; if (i < a.blocks.size()) remA = a.blocks[i].count; } if (remB == 0) { ++j; if (j < b.blocks.size()) remB = b.blocks[j].count; } } return answer; } int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { Kind sourceKind = classify(a, b); Kind targetKind = classify(c, d); if (sourceKind == ZERO_KIND) { return targetKind == ZERO_KIND ? 0 : -1; } if (sourceKind == AXIS_KIND) { if (a == c && b == d) return 0; int64 nonzero = (a != 0 ? a : b); bool matchingSign = (nonzero > 0 && targetKind == POSITIVE_KIND) || (nonzero < 0 && targetKind == NEGATIVE_KIND); if (!matchingSign) return -1; if (gcd64(magnitude(c), magnitude(d)) != magnitude(nonzero)) { return -1; } // (x,0) -> (x,x), or (0,x) -> (x,x). Path targetPath = buildPath(magnitude(c), magnitude(d)); return 1 + targetPath.length; } if (sourceKind == POSITIVE_KIND || sourceKind == NEGATIVE_KIND) { // A strictly same-sign state can never change its sign class. if (targetKind != sourceKind) return -1; if (gcd64(magnitude(a), magnitude(b)) != gcd64(magnitude(c), magnitude(d))) { return -1; } Path sourcePath = buildPath(magnitude(a), magnitude(b)); Path targetPath = buildPath(magnitude(c), magnitude(d)); if (!isPrefix(sourcePath, targetPath)) return -1; return targetPath.length - sourcePath.length; } // The source has opposite nonzero signs. // Canonicalize it to (positive, negative), swapping the target too. if (a < 0) { swap(a, b); swap(c, d); } targetKind = classify(c, d); int64 g = gcd64(a, magnitude(b)); if (targetKind == MIXED_KIND) { // The coordinate containing the positive value cannot change. if (!(c > 0 && d < 0)) return -1; if (gcd64(magnitude(c), magnitude(d)) != g) return -1; Path sourcePath = buildPath(a, magnitude(b)); Path targetPath = buildPath(c, magnitude(d)); // The target must be an ancestor of the source in the positive tree. if (!isPrefix(targetPath, sourcePath)) return -1; return sourcePath.length - targetPath.length; } if (targetKind == POSITIVE_KIND || targetKind == NEGATIVE_KIND) { if (gcd64(magnitude(c), magnitude(d)) != g) return -1; Path sourcePath = buildPath(a, magnitude(b)); Path targetPath = buildPath(magnitude(c), magnitude(d)); // A positive exit corresponds to an 'A'-ending candidate path. // A negative exit corresponds to a 'B'-ending candidate path. char required = (targetKind == POSITIVE_KIND ? 'A' : 'B'); int64 k = lcpMirrored(sourcePath, targetPath); if (k < sourcePath.length && k < targetPath.length && sourcePath.charAt(k) == required && targetPath.charAt(k) == required) { return sourcePath.length + targetPath.length - 2 * k - 1; } // No direct exit reaches the target. Go through equal magnitudes: // (g,-g) -> (g,0) -> (g,g), or // (g,-g) -> (0,-g) -> (-g,-g). return sourcePath.length + targetPath.length + 2; } if (targetKind == AXIS_KIND) { Path sourcePath = buildPath(a, magnitude(b)); if (c > 0 && d == 0 && c == g) { return sourcePath.length + 1; } if (c == 0 && d < 0 && magnitude(d) == g) { return sourcePath.length + 1; } return -1; } return -1; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; string output; output.reserve(static_cast<size_t>(Q) * 24); while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; output += to_string(solveQuery(a, b, c, d)); output += '\n'; } cout << output; return 0; }
#include <bits/stdc++.h> using namespace std; using int64 = long long; static constexpr int MAX_RUNS = 256; struct Run { char ch; int64 len; }; struct Path { int count = 0; int64 length = 0; Run runs[MAX_RUNS]; }; /* For positive x and y, repeatedly subtract the smaller value from the larger one until reaching (g,g), where g = gcd(x,y). Reversing these subtractions gives a word over: A: (x,y) -> (x+y,y) B: (x,y) -> (x,y+x) The word is stored in run-length encoded form. */ void buildPath(int64 x, int64 y, Path& path) { Run reversedRuns[MAX_RUNS]; int count = 0; int64 length = 0; while (x != y) { if (x > y) { int64 k = (x - 1) / y; reversedRuns[count++] = {'A', k}; x -= k * y; length += k; } else { int64 k = (y - 1) / x; reversedRuns[count++] = {'B', k}; y -= k * x; length += k; } } path.count = count; path.length = length; for (int i = 0; i < count; ++i) { path.runs[i] = reversedRuns[count - 1 - i]; } } char opposite(char ch) { return ch == 'A' ? 'B' : 'A'; } /* Longest common prefix of two paths. If flipFirst is true, every A/B in the first path is interchanged. */ int64 commonPrefix(const Path& first, const Path& second, bool flipFirst) { int i = 0, j = 0; int64 remainingFirst = first.count ? first.runs[0].len : 0; int64 remainingSecond = second.count ? second.runs[0].len : 0; int64 result = 0; while (i < first.count && j < second.count) { char firstChar = flipFirst ? opposite(first.runs[i].ch) : first.runs[i].ch; char secondChar = second.runs[j].ch; if (firstChar != secondChar) break; int64 take = min(remainingFirst, remainingSecond); result += take; remainingFirst -= take; remainingSecond -= take; if (remainingFirst == 0) { ++i; if (i < first.count) remainingFirst = first.runs[i].len; } if (remainingSecond == 0) { ++j; if (j < second.count) remainingSecond = second.runs[j].len; } } return result; } /* Largest position n <= cap such that both paths contain the requested character at position n. Positions are zero-indexed. */ int64 lastCommonDesiredPosition( const Path& first, const Path& second, char desired, int64 cap ) { if (cap < 0) return -1; int i = 0, j = 0; int64 positionFirst = 0, positionSecond = 0; int64 remainingFirst = first.count ? first.runs[0].len : 0; int64 remainingSecond = second.count ? second.runs[0].len : 0; int64 answer = -1; while (i < first.count && j < second.count) { int64 endFirst = positionFirst + remainingFirst; int64 endSecond = positionSecond + remainingSecond; if (first.runs[i].ch == desired && second.runs[j].ch == desired) { int64 low = max(positionFirst, positionSecond); int64 high = min(endFirst, endSecond); // exclusive if (low < high) { int64 candidate = min(high - 1, cap); if (candidate >= low) { answer = max(answer, candidate); } } } int64 take = min(remainingFirst, remainingSecond); positionFirst += take; positionSecond += take; remainingFirst -= take; remainingSecond -= take; if (remainingFirst == 0) { ++i; if (i < first.count) remainingFirst = first.runs[i].len; } if (remainingSecond == 0) { ++j; if (j < second.count) remainingSecond = second.runs[j].len; } } return answer; } bool isPrefix(const Path& prefix, const Path& path) { return commonPrefix(prefix, path, false) == prefix.length; } int signOf(int64 x) { return (x > 0) - (x < 0); } int64 absoluteValue(int64 x) { return x < 0 ? -x : x; } enum Kind { ZERO_ZERO, ZERO_ONE, SAME_SIGN, MIXED_SIGN }; Kind classify(int64 x, int64 y) { if (x == 0 && y == 0) return ZERO_ZERO; if (x == 0 || y == 0) return ZERO_ONE; if ((x > 0) == (y > 0)) return SAME_SIGN; return MIXED_SIGN; } int64 solveQuery(int64 a, int64 b, int64 c, int64 d) { if (a == c && b == d) return 0; int64 sourceGcd = gcd(absoluteValue(a), absoluteValue(b)); int64 targetGcd = gcd(absoluteValue(c), absoluteValue(d)); // The gcd is invariant under both operations. if (sourceGcd != targetGcd) return -1; Kind sourceKind = classify(a, b); Kind targetKind = classify(c, d); if (sourceKind == ZERO_ZERO) { return -1; } if (sourceKind == ZERO_ONE) { // The only meaningful operation creates (x,x). if (targetKind != SAME_SIGN) return -1; int64 sourceSign = signOf(a != 0 ? a : b); if (signOf(c) != sourceSign) return -1; Path targetPath; buildPath(absoluteValue(c), absoluteValue(d), targetPath); return 1 + targetPath.length; } if (sourceKind == SAME_SIGN) { // The sign cannot change, and the target must be a descendant // of the source in the positive Euclidean tree. if (targetKind != SAME_SIGN) return -1; if (signOf(c) != signOf(a)) return -1; Path sourcePath, targetPath; buildPath(absoluteValue(a), absoluteValue(b), sourcePath); buildPath(absoluteValue(c), absoluteValue(d), targetPath); if (!isPrefix(sourcePath, targetPath)) return -1; return targetPath.length - sourcePath.length; } // The source has opposite signs. if (targetKind == ZERO_ZERO) { return -1; } if (targetKind == ZERO_ONE) { Path sourcePath; buildPath(absoluteValue(a), absoluteValue(b), sourcePath); // Equality must first be reached. Then either coordinate can be // changed into zero, retaining the sign of the other coordinate. bool valid = (c == 0 && d == signOf(b) * sourceGcd) || (d == 0 && c == signOf(a) * sourceGcd); if (!valid) return -1; return sourcePath.length + 1; } if (targetKind == MIXED_SIGN) { // While the signs are opposite, staying mixed forces us to update // the coordinate with larger absolute value. if (signOf(c) != signOf(a) || signOf(d) != signOf(b)) { return -1; } Path sourcePath, targetPath; buildPath(absoluteValue(a), absoluteValue(b), sourcePath); buildPath(absoluteValue(c), absoluteValue(d), targetPath); if (!isPrefix(targetPath, sourcePath)) return -1; return sourcePath.length - targetPath.length; } // Mixed-sign source, same-sign target. Path sourcePath, targetPath; buildPath(absoluteValue(a), absoluteValue(b), sourcePath); buildPath(absoluteValue(c), absoluteValue(d), targetPath); // A is wanted when the first coordinate has the target sign. // Otherwise B is wanted. char wanted = signOf(c) == signOf(a) ? 'A' : 'B'; /* For a prefix R L of the source path, exiting the mixed-sign region toward the desired sign produces a positive path equal to swap(R) L, where swap interchanges A and B. If n = |R|, this candidate is a prefix of the target exactly when: - the first n target characters equal the first n characters of swap(P), - P[n] = wanted, - T[n] = wanted. */ int64 matched = commonPrefix(sourcePath, targetPath, true); int64 cap = min(matched, min(sourcePath.length, targetPath.length) - 1); int64 n = lastCommonDesiredPosition( sourcePath, targetPath, wanted, cap ); if (n >= 0) { int64 k = n + 1; return sourcePath.length + targetPath.length - 2 * k + 1; } /* No earlier exit works. Continue to equality (g,-g), use two operations to reach either (g,g) or (-g,-g), and then follow the target's tree path. */ return sourcePath.length + targetPath.length + 2; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int Q; cin >> Q; while (Q--) { int64 a, b, c, d; cin >> a >> b >> c >> d; cout << solveQuery(a, b, c, d) << '\n'; } return 0; }