Dang_Quan_10_Tin

ROBOT

Aug 13th, 2020
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdio>
  3. #include <algorithm>
  4. #include <cmath>
  5. #define task "ROBOT"
  6. using namespace std;
  7. using ll = long long;
  8. using ld = long double;
  9.  
  10. const int N = 1e5 + 2;
  11. ll a, b, c;
  12. ll x, y, u, v;
  13. const ll Inf = 1e18;
  14.  
  15. void Read()
  16. {
  17.     cin >> a >> b >> c;
  18. }
  19.  
  20. pair<ll, ll> Euclid(ll a, ll b)
  21. {
  22.     ll xa = 1, xb = 0, ya = 0, yb = 1, xr, yr;
  23.     ll r, q;
  24.     while (b != 0)
  25.     {
  26.         q = a / b;
  27.         r = a - b * q;
  28.         xr = xa - xb * q;
  29.         yr = ya - yb * q;
  30.         a = b;
  31.         xa = xb;
  32.         ya = yb;
  33.         b = r;
  34.         xb = xr;
  35.         yb = yr;
  36.     }
  37.     return {xa, ya};
  38. }
  39.  
  40. void Solve()
  41. {
  42.     ll d = __gcd(a, b);
  43.     if (c % d != 0)
  44.     {
  45.         cout << "-1\n";
  46.         return;
  47.     }
  48.     pair<ll, ll> s = Euclid(a, b);
  49.     x = s.first;
  50.     y = s.second;
  51.     x *= c / d;
  52.     y *= c / d;
  53.     //cout << x << " " << y << "\n";
  54.     ll p = b / d, q = -a / d;
  55.     ll posx = (x % p + p) % p;
  56.     y = y - (x - posx) / p * q;
  57.     x = posx;
  58.     //cout << x << " " << y << "\n";
  59.     ll ans = Inf;
  60.     if (y <= 0)
  61.     {
  62.         if (ans > abs(x) + abs(y))
  63.         {
  64.             ans = abs(x) + abs(y);
  65.             u = x;
  66.             v = y;
  67.         }
  68.     }
  69.     ll posy = (y % abs(q) - abs(q)) % abs(q);
  70.     x = x + (y - posy) / abs(q) * p;
  71.     y = posy;
  72.     //cout << x << " " << y << "\n";
  73.     if (x >= 0)
  74.     {
  75.         if (ans > abs(x) + abs(y))
  76.         {
  77.             ans = abs(x) + abs(y);
  78.             u = x;
  79.             v = y;
  80.         }
  81.     }
  82.     //cout << u << " " << v << "\n";
  83.     if (ans == Inf)
  84.     {
  85.         cout << "-1\n";
  86.         return;
  87.     }
  88.     cout << ans << "\n";
  89. }
  90.  
  91. int32_t main()
  92. {
  93.     ios::sync_with_stdio(0);
  94.     cin.tie(0);
  95.     cout.tie(0);
  96.     if (fopen(task ".INP", "r"))
  97.         freopen(task ".INP", "r", stdin),
  98.             freopen(task ".OUT", "w", stdout);
  99.     int t;
  100.     cin >> t;
  101.     while (t--)
  102.         Read(),
  103.             Solve();
  104. }
Advertisement
Add Comment
Please, Sign In to add comment