PROBLEM LINK:
Author: Roman Rubanenko
Tester: Shiplu Hawlader
Editorialist: Praveen Dhinwa
DIFFICULTY:
Medium
PREREQUISITES:
Simple Math.
PROBLEM:
Given N.
Let A = {1, 2, , N} and B = {N + 1, , 2 * N}.
Let C contains elements representing sum of pairs of A and B. Note that C is a multiset.
You will be given queries in which you are asked to find cnt of q in C.
Explanation
Note that entries in C will be between N + 2 to 3N.
Given a q, how to find cnt of q in C?
Let us say that number selected from A is x and from B is y.
So x + y = q.
Rewrite as x = q - y.
We see that y should satisfy following inequalities.
N + 1 <= y <= 2N i.e. 1 <= q - y <= N.
You can see that count of valid y will be answer of our problem.
Can you get value of count of valid y from the above inequalities?
Yes, Rewrite both the inequalities as follows.
1 <= q - y <= N will become q - N <= y <= q - 1.
N + 1 <= y <= 2N
So we notice that y should be at least max(q - N, N + 1) and at most min(q - 1, 2N).
Now, can you find count of valid y’s?
Yes, if y lies in the range [L, R], then answer will be R - L + 1.
Note that if L > R, then there is no solution.
Pseudo Code
long L = max(q - N, N + 1);
long R = min(q - 1, 2N);
long long ans = 0;
if (L > R)
ans = 0;
else
ans = R - L + 1;
Few Small Points
- Note that q can overflow from long data type because q can go upto 3 * 10^9. You should use long long data type.
Complexity:
For each query, we are just doing a constant number of operations. So for each test case, if there are queries, our time complexity
will be O(m) per test case.