I recently learned such a thing as "Find the number of pairs in two arrays such that their sum is equal to X" and this is all for O (n + m).
But I got a slightly different problem, but I could not solve it by this method. Briefly about the condition:
Given two arrays A and B and the number N. It is necessary to find the number of numbers p (from 1 to N) such that (p div Ai) == (p mod Bj).
Limitations:
N, Ai, Bi <= 10 ^ 5
n, m <= 200
Example:
7 2 2 3 4 2 3
Conclusion:
five
Explanation:
The numbers [2,3,4,5,7] are suitable for us because there are pairs: (2 div 3 == 2 mod 2), (3 div 3 == 3 mod 2), (4 div 3 == 4 mod 3 ), (5 div 3 == 5 mod 2), (7 div 4 == 7 mod 3).
My attempt:
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { int n, a, b; scanf("%d%d%d", &n, &a, &b); vector <int> arr1(a); for (int i = 0; i < a; i++) { scanf("%d", &arr1[i]); } vector <int> arr2(b); for (int i = 0; i < b; i++) { scanf("%d", &arr2[i]); } sort(arr1.begin(), arr1.end()); sort(arr2.begin(), arr2.end()); int total = 0; for (int p = 1; p <= n; p++) { int i = 0; int j = b - 1; while (i < a && j >= 0) { if (p / arr1[i] == p % arr2[j]) { total++; break; } else if (p / arr1[i] < p % arr2[j]) { j--; } else i++; } } printf("%d", total); return 0; }