---
id: 1297
lang: en
translation_of: index.md
source_sha256: 6d0d0a2e117517ef6d0c6ecf577efc91d39c0a8aa42b8dccd5ea2c5b23c381ca
title: "LibreOJ 3096: [SNOI2019] Number Theory — Solution"
description: "Enumerate numbers in the residue system of Q; they lie on a cycle, so keep prefix sums of their contributions and compare ranks to pick the direction."
tags: ["OI","Number Theory","LibreOJ","Residue Systems","Modular Arithmetic"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## Solution

First, within the residue system of $Q$ we enumerate numbers $x_0$, and write each of them as $x = (x_0 + k * P) \mod Q$. Thinking about it a bit, we find that these numbers change with $k$, and they show a periodic pattern: that is, these numbers lie on a cycle. We can consider recording, for every number in the residue system of $Q$, its contribution in $P$, recording it as prefix sums, and when computing the answer, compare ranks to determine the direction around the cycle (the long arc or the short arc).

For the details, just look at the code. Savor it carefully and you should be able to understand it.

<!--more-->

## Code

```cpp
// LOJ3096.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int MAX_N = 1e6 + 2000;
ll p, q, n, m, t, ai[MAX_N], bi[MAX_N], sum[MAX_N], tot[MAX_N], len, ans;
int key[MAX_N], rk[MAX_N];
bool vis[MAX_N];

ll gcd(ll x, ll y) { return y == 0 ? x : gcd(y, x % y); }

int main()
{
    scanf("%lld%lld%lld%lld%lld", &p, &q, &n, &m, &t);
    len = q / gcd(p, q);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &ai[i]);
    for (int i = 1; i <= m; i++)
    {
        scanf("%lld", &bi[i]), sum[bi[i]]++;
        key[bi[i]] = 1;
    }
    for (int i = 0; i < q; i++)
    {
        if (vis[i])
            continue;
        vis[i] = true;
        int now, last = i;
        rk[i] = 1;
        for (now = (last + p) % q; now != i; last = now, now = (now + p) % q)
            rk[now] = rk[last] + 1, sum[now] += sum[last], vis[now] = true;
        tot[i] = sum[last];
        for (int j = (i + p) % q; j != i; j = (j + p) % q)
            tot[j] = sum[last];
    }
    for (int i = 1; i <= n; i++)
    {
        if (ai[i] >= t)
            continue;
        ll cnt = (t - 1 - ai[i]) / p;
        ll A = ai[i] % q, B = (A + cnt % len * p) % q;
        ans += cnt / len * tot[A];
        if (rk[A] <= rk[B])
            ans += sum[B] - sum[A] + key[A];
        else
            ans += tot[A] - (sum[A] - sum[B] - key[A]);
    }
    printf("%lld", ans);
    return 0;
}
```
