Olympiad in Informatics

LibreOJ#3144. [APIO 2019] Strange Device — Solution

Main Idea

I derived three bogus cycles on my own, and so off I ran to the solution.

First, let the period be \(k\), and consider the final state \(x = 0, y = 0\). We consider what kind of period can go through one iteration and give the same state \(x = 0, y = 0\). We might as well substitute \(k\) directly:

\[ x = (k + \lfloor \frac{k}{B} \rfloor) \bmod A, y = k \bmod B \]

Here the final state is \(x = 0, y = 0\), so we get the information \(B | k\). Now the floor no longer does anything, which gives:

\[ \begin{aligned} k + \frac{k}{B} &\equiv 0 \pmod A \\ k(B + 1) &\equiv 0 \pmod A \end{aligned} \]

After working this thing out, we can break out of the modular restriction and get:

\[ \begin{aligned} k(B + 1) &= Ai \\ k &= i \cdot \frac{A}{B + 1} \end{aligned} \]

Since \(k\) is an integer, \(i\) needs to satisfy:

\[ i = j \frac{B + 1}{\gcd(A, B + 1)} \]

Adding the condition \(B | k\), we easily get:

\[ i = j B \frac{B + 1}{\gcd(A, B + 1)} \]

So the period is:

\[ \begin{aligned} k &= j B \frac{B + 1}{\gcd(A, B + 1)} \cdot \frac{A}{B + 1} \\ &= j \frac{AB}{\gcd(A, B + 1)} \\ k &\equiv 0 \pmod {\frac{AB}{\gcd(A, B + 1)}} \end{aligned} \]

Code

// LOJ3144.cpp
#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

const int MAX_N = 1e6 + 200;

ll n, A, B, loop, cnt;
pair<ll, ll> segs[MAX_N << 1];

ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }

int main()
{
    scanf("%lld%lld%lld", &n, &A, &B);
    loop = A / gcd(A, B + 1) * B;
    for (int i = 1; i <= n; i++)
    {
        ll l, r;
        scanf("%lld%lld", &l, &r);
        if (r - l + 1 >= loop)
            printf("%lld\n", loop), exit(0);
        l %= loop, r %= loop;
        if (l <= r)
            segs[++cnt] = make_pair(l, r);
        else
            segs[++cnt] = make_pair(l, loop - 1), segs[++cnt] = make_pair(0, r);
    }
    sort(segs + 1, segs + 1 + cnt);
    segs[++cnt] = make_pair(loop + 1, 0);
    ll lft = segs[1].first, rig = segs[1].second, ans = 0;
    for (int i = 2; i <= cnt; i++)
    {
        if (rig < segs[i].first)
        {
            ans += rig - lft + 1;
            lft = segs[i].first, rig = segs[i].second;
        }
        else
            rig = max(rig, segs[i].second);
    }
    printf("%lld\n", ans);
    return 0;
}