Advertisement
istinishat

Linear Diophantine Equation

May 6th, 2018
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //problem : http://codeforces.com/contest/633/problem/A
  2. //code from : https://e-maxx-eng.appspot.com/algebra/linear-diophantine-equation.html
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7. int gcd(int a, int b, int &x, int &y) {
  8.     if (a == 0) {
  9.         x = 0; y = 1;
  10.         return b;
  11.     }
  12.     int x1, y1;
  13.     int d = gcd(b%a, a, x1, y1);
  14.     x = y1 - (b / a) * x1;
  15.     y = x1;
  16.     return d;
  17. }
  18.  
  19. bool find_any_solution(int a, int b, int c, int &x0, int &y0, int &g) {
  20.     g = gcd(abs(a), abs(b), x0, y0);
  21.    // cout<<g<<endl;
  22.     if (c % g) {
  23.         return false;
  24.     }
  25.     //cout<<x0<<' '<<y0<<endl;
  26.  
  27.     x0 *= c / g;
  28.     y0 *= c / g;
  29.     if (a < 0) x0 = -x0;
  30.     if (b < 0) y0 = -y0;
  31.     return true;
  32. }
  33.  
  34. void shift_solution (int & x, int & y, int a, int b, int cnt) {
  35.     x += cnt * b;
  36.     y -= cnt * a;
  37. }
  38.  
  39. int find_all_solutions (int a, int b, int c, int minx, int maxx, int miny, int maxy) {
  40.     int x, y, g;
  41.     if (! find_any_solution (a, b, c, x, y, g))
  42.         return 0;
  43.     a /= g;  b /= g;
  44.  
  45.     int sign_a = a>0 ? +1 : -1;
  46.     int sign_b = b>0 ? +1 : -1;
  47.  
  48.     shift_solution (x, y, a, b, (minx - x) / b);
  49.     if (x < minx)
  50.         shift_solution (x, y, a, b, sign_b);
  51.     if (x > maxx)
  52.         return 0;
  53.     int lx1 = x;
  54.  
  55.     shift_solution (x, y, a, b, (maxx - x) / b);
  56.     if (x > maxx)
  57.         shift_solution (x, y, a, b, -sign_b);
  58.     int rx1 = x;
  59.  
  60.     shift_solution (x, y, a, b, - (miny - y) / a);
  61.     if (y < miny)
  62.         shift_solution (x, y, a, b, -sign_a);
  63.     if (y > maxy)
  64.         return 0;
  65.     int lx2 = x;
  66.  
  67.     shift_solution (x, y, a, b, - (maxy - y) / a);
  68.     if (y > maxy)
  69.         shift_solution (x, y, a, b, sign_a);
  70.     int rx2 = x;
  71.  
  72.     if (lx2 > rx2)
  73.         swap (lx2, rx2);
  74.     int lx = max (lx1, lx2);
  75.     int rx = min (rx1, rx2);
  76.  
  77.     return (rx - lx) / abs(b) + 1;
  78. }
  79.  
  80. int main()
  81. {
  82.     int a,b,c;
  83.     int x,y,g;
  84.     cin>>a>>b>>c;
  85.     int flag=find_all_solutions(a,b,c,0,1000000,0,1000000);
  86.     if(flag)printf("Yes\n");
  87.     else printf("No\n");
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement