tokaisu's blog

By tokaisu, history, 4 hours ago, In English

I know the problem is pretty old now but I just learned about Diophantine equations and this is one of the practice problems. Here's my solution:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
 
ll extgcd(ll a, ll b, ll &x, ll &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    ll x1, y1;
    ll d = extgcd(b, a%b, x1, y1);
    x = y1;
    y = x1 - y1*(a/b);
    return d;
}
 
void solve() {
    ll a, b, c; cin >> a >> b >> c;
    c = -c;
    ll x1, x2; cin >> x1 >> x2;
    ll y1, y2; cin >> y1 >> y2;
    ll ans;
    if (x1 > x2 || y1 > y2) {
        ans = 0;
    }
    else if (a == 0 && b == 0) {
        if (c == 0) ans = (x2-x1+1)*(y2-y1+1);
        else ans = 0;
    }
    else if (a == 0 && b != 0) {
        if (c % b == 0) {
            ll q = c/b;
            if (y1 <= q && q <= y2) ans = (x2-x1+1);
            else ans = 0;
        }
        else ans = 0;
    }
    else if (a != 0 && b == 0) {
        if (c % a == 0) {
            ll q = c/a;
            if (x1 <= q && q <= x2) ans = (y2-y1+1);
            else ans = 0;
        }
        else ans = 0;
    }
    else {
        ll x, y;
        ll d = extgcd(abs(a), abs(b), x, y);
        if (c % d != 0) {
            ans = 0;
        }
        else {
            ll ad = a/d;
            ll bd = b/d;
            x *= (c/d);
            y *= (c/d);
            if (x < 0) x = -x;
            if (y < 0) y = -y;
            ll min_kx = (x1-x+bd-1)/bd;
            ll max_kx = (x2-x)/bd;
            ll min_ky = (y-y2+ad-1)/ad, max_ky = (y-y1)/ad;
            if (max_kx >= min_ky || max_ky >= min_kx) {
                ans = min(max_kx, max_ky) - max(min_kx, min_ky) + 1;
            }
            else ans = 0;
        }
    }
    cout << ans;
}
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    for (int i = 1; i <= t; i++) {
        solve();
    }
}

I tried every way to fix this but still got WA on the 3rd test case. Can anybody help? Really appreciate it.

  • Vote: I like it
  • -5
  • Vote: I do not like it