Блог пользователя Nanthakumar06

Автор Nanthakumar06, 6 месяцев назад, По-английски

You are given an array A of size N and a number C.

We define the beauty number of a number X is defined as:

  • We have a universal array U where all the integers from -10^18 to 10^18 are present in sorted order [10^18,1-10^18,......,0,1,2,3,......10^18].
  • Now the beauty number of X is the number of subarrays of U with the sum X.

Find the number of elements in array A whose beauty number is strictly greater than C.

Constraints:

  • 1<=N<=10^5
  • 1<=C<=10^12
  • 1<=A[i]<=10^5

Test cases:

  • N = 1, C = 2, A = [12] Output: 1 The beauty number of 12 is 4. the result is 1. [12],[3,4,5],[-2,-1,0,1,2,3,4,5],[-11,-10,.....12]

  • N = 1, C = 12, A = [2] the beauty number of 2 is 2([2],[-1,0,1,2]

Can anyone help me to solve this

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
6 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Here is my solution to the problem. The key idea is as follows: if we can calculate the beauty of each number of array $$$A$$$ fast enough, then we can just simply calculate the beauty of each element of array $$$A$$$ and check if it's greater than $$$C$$$. So, the question is how to find the number of subarrays of $$$U$$$ with sum equal $$$X$$$?

Imagine that we have subarray $$$[a, a + 1, a + 2, \dots , b - 1, b]$$$ of universal array. One can notice that this sequence of numbers is an arithmetic progression where the first element is equal to $$$a$$$, common difference is equal to $$$1$$$ and the length is equal to $$$b - a + 1$$$. Because of that, we can use a specialized formula to calculate the sum of the subarray: $$$S=\frac{(b - a + 1)(a + b)}{2}$$$. Now it's obvious that to calculate the beauty of the number $$$X$$$ we need to find the number of pairs $$$(a, b)$$$ where $$$-10^{18} \le a \le b \le 10^{18}$$$ such that $$$(b - a + 1)(a + b)=2X$$$.

Since $$$a, b$$$ were integers, values of $$$b - a + 1$$$ and $$$a + b$$$ are also integers, so $$$a + b$$$ is one of the divisors of $$$2X$$$. Imagine that we have a list of all divisors of $$$2X$$$. We can use this list to brute force the value $$$a + b$$$. Then we can use it to calculate $$$a-b=1-\frac{2X}{a+b}$$$. The only things remains is to check that $$$a, b$$$ satisfy the following requiremenets: $$$-10^{18} \le a \le b \le 10^{18}$$$. And now the last question: how to find all divisors of $$$X$$$?

The naive approach with the complexity of $$$O(\sqrt{X})$$$ should work just great for your constraints.

Hope it helps.