D - 183183 Editorial by en_translator
Consider, when \(i\) and the number of digits of \(A_j\) is fixed, how we can count the number of \(j\) satisfying the conditions.
Let \(k\) be the number of digits of \(A_j\). Then \(f(A_i,A_j)=10^{k}A_i+A_j\). Therefore, \(f(A_i,A_j)\) is a multiple of \(M\) if and only if \(A_j \equiv -10^{k}A_i \bmod M\).
The number of \(j\) can be instantly obtained if we maintain a map with keys \(A_j \bmod M\) for \(j\) such that \(A_j\) has \(k\) digits, for each \(k\). Alternatively, instead of using maps, we can perform a binary search on a list containing \(A_j \bmod M\) in ascending order; this runs faster though the complexity is the same.
There are \(O(N)\) values for \(i\) and \(O(\log \max_i A_i)\) values for \(O(\log \max_i A_i)\), and for fixed \(i,k\) the number of \(j\) satisfying the conditions can be computed in \(O(\log N)\) time, so the overall time complexity is \(O(N \log \max_i A_i \log N)\).
The problem can be solved by appropriately implementing this algorithm.
Sample code (Python 3)
import bisect
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = list(map(int, input().split()))
g = [[] for _ in range(11)]
for v in a:
g[len(str(v))].append(v % m)
for gg in g:
gg.sort()
ans = 0
for ai in a:
for k in range(1, 11):
ai = (ai * 10) % m
key = (m - ai) % m
ans += bisect.bisect_left(g[k], key + 1) - bisect.bisect_left(g[k], key)
print(ans)
Sample code (C++)
#include <bits/stdc++.h>
using namespace std;
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
int n;
long long m;
cin >> n >> m;
vector<int> a(n);
for (int &v : a)
cin >> v;
vector<vector<int>> g(11);
for (int v : a)
g[to_string(v).size()].push_back(v % m);
for (auto &gg : g)
sort(gg.begin(), gg.end());
long long ans = 0;
for (long long ai : a) {
for (int k = 1; k < 11; k++) {
ai *= 10, ai %= m;
const int key = (m - ai) % m;
ans += lower_bound(g[k].begin(), g[k].end(), key + 1) - lower_bound(g[k].begin(), g[k].end(), key);
}
}
cout << ans << endl;
}
posted:
last update: