Problem for Zenik
Limits: 2 sec., 256 MiB
This statement was translated automatically from Ukrainian.
Today Marichka told Zenik an interesting problem.
There is an array consisting of \(n\) elements. How many intervals \([l, r]\) exist such that:
\(1 \le l \le r \le n\),
\(a_l + a_{l+1} + \ldots + a_{r-1} + a_r < k\).
Zenik wants to impress the girl, so he is trying his best to solve this problem.
Can you handle this problem too?
Input
The first line contains an integer \(n\) — the size of the array.
The second line contains \(n\) integers \(a_i\) — the elements of the array.
The third line contains an integer \(k\).
Output
Print a single integer in a single line — the answer to the problem. Pay attention that the answer can exceed \(10^{9}\).
Constraints
44% of tests:
\(1 \le n \le 1474\),
\(|a_i|, |k| \le 10^{6}\),
56% of tests:
\(1 \le n \le 147474\),
\(|a_i|, k \le 10^{9}\).
Samples
| Input (stdin) | Output (stdout) |
|---|---|
| 4 1 1 1 2 3 | 6 |
Notes
There are 6 intervals satisfying the problem condition:
\([1, 1]\), \([2, 2]\), \([3, 3]\), \([4, 4]\), \([1, 2]\), \([2, 3]\).
Submit a solution
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|
Задача для Зеника - Розбір
Нехай \(P_0 = 0\), \(P_i = a_1 + \ldots + a_i\) — префіксні суми. Сума на проміжку \([l, r]\) дорівнює \(P_r - P_{l-1}\), тому потрібно порахувати кількість пар \(0 \le i < j \le n\) з \(P_j < P_i + k\). Елементи можуть бути від’ємними, тож метод двох вказівників тут не працює.
Будемо перебирати \(i\) і рахувати, скільки серед \(P_{i+1}, \ldots, P_n\) значень, менших за \(P_i + k\). Для цього посортуємо всі префіксні суми (стиснемо координати) і заведемо дерево Фенвіка, у якому спочатку позначені всі \(P_1, \ldots, P_n\). Переходячи до наступного \(i\), видаляємо з дерева \(P_i\), а кількість потрібних значень знаходимо бінарним пошуком позиції \(P_i + k\) серед посортованих сум і запитом суми на префіксі дерева.
Складність — \(O(n \log n)\).
Відповідь може перевищувати \(10^9\), а
суми — \(10^{14}\), тому потрібен
long long.
| Element Type | Created | Who | Problem | Compiler | Result | Time (sec.) | Memory (MiB) | # | Actions |
|---|