Olympiad in Informatics

POJ2891: Strange Way to Express Integers — Solution

Approach

Well, for a math scrub like me, writing math problems really is a miserable experience.

First, analyzing the problem: it obviously gives some linear congruences and asks us to solve them. But unlike with the Chinese Remainder Theorem, this problem does not guarantee that the moduli are coprime.

\[ \begin{gathered} x \equiv a_1 (mod\ m_1) \\ x \equiv a_2 (mod\ m_2) \\ x \equiv a_3 (mod\ m_3) \\ \dots \\ x \equiv a_i (mod\ m_i) \end{gathered} \]

But we can still solve this with the good old extended Euclidean algorithm: just merge the equations.

Suppose we are solving the \(k\)-th equation. Let \(m=\prod_{i=1}^{k-1}\), and let \(x\) be a solution satisfying equations \(1\)~\(k-1\). We know that \(tm+x\) is the general solution of the first \(k-1\) equations, so in this round we only need to find \(k\) and update the answer, that is, solve:

\[ \begin{gathered} tm_{k-1} + x_{k-1} \equiv a_k(mod\ m_k) \\ tm_{k-1} + m_k y \equiv a_k - x_{k-1}(mod\ m_k) \end{gathered} \]

Just plug it into \(exgcd\) and solve it.

Code

// POJ2891.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int MAX_N = 1e6 + 200;
ll exgcd(ll a, ll b, ll &x, ll &y)
{
    if (b == 0)
    {
        x = 1, y = 0;
        return a;
    }
    ll d = exgcd(b, a % b, x, y), z = x;
    x = y, y = z - (a / b) * y;
    return d;
}
int main()
{
    ll n;
    while (~scanf("%lld", &n))
    {
        ll x, y, a, b, k;
        scanf("%lld%lld", &a, &b);
        ll lcm = a, ans = b;
        bool flag = true;
        n--;
        while (n--)
        {
            scanf("%lld%lld", &a, &b);
            b = (b - ans % a + a) % a;
            ll d = exgcd(lcm, a, x, y);
            if (b % d)
                flag = false;
            else
                k = x * (b / d);
            ans += k * lcm;
            lcm = lcm / d * a;
            ans = (ans % lcm + lcm) % lcm;
        }
        if (flag)
            printf("%lld\n", ans);
        else
            puts("-1");
    }
    return 0;
}