To solve the problem of finding the number of contiguous subsequences in sequence ( A ) where the absolute value of their sum is greater than a given positive integer ( S ), we can use the Prefix Sum technique combined with Binary Indexed Trees (Fenwick Trees) for efficient range queries and updates.
Here's a step-by-step explanation and an implementation in C++:
Step-by-Step Explanation
-
Prefix Sum Calculation:
- Compute the prefix sums of the array ( A ). The prefix sum at index ( j ) is the sum of all elements from the start up to index ( j ).
- This allows us to compute the sum of any contiguous subarray ( A[i \ldots j] ) as ( \text{prefix}[j] - \text{prefix}[i-1] ).
-
Handling Absolute Values:
- Since we need the absolute value of the sum to be greater than ( S ), we can break this down into two separate cases:
- ( \text{sum} > S )
- ( \text{sum} < -S )
- We will count the number of subarrays satisfying each condition and sum them up.
-
Coordinate Compression:
- To efficiently use a Fenwick Tree, which requires indexing in a compressed coordinate system, we collect all relevant prefix sums and their adjusted values (i.e., ( \text{prefix}[j] - S ) and ( \text{prefix}[j] + S )).
- We sort these values and assign a unique index to each to facilitate quick querying and updating.
-
Using Fenwick Trees:
- We use two Fenwick Trees to handle the two cases separately.
- For each position ( j ) in the array:
- Case 1 (( \text{sum} > S )):
- We count how many prefix sums before ( j ) are less than ( \text{prefix}[j] - S ).
- Case 2 (( \text{sum} < -S )):
- We count how many prefix sums before ( j ) are greater than ( \text{prefix}[j] + S ).
- These counts are accumulated to get the final answer.
-
Final Count:
- The total number of valid subarrays is the sum of the counts from both cases.
C++ Implementation
Below is a C++ program that implements the above approach. It reads the input from CNTSEQ.INP and writes the result to CNTSEQ.OUT. Make sure to place the input in CNTSEQ.INP and run the program in an environment where file I/O is supported.
#include <bits/stdc++.h>
using namespace std;
// Fenwick Tree (Binary Indexed Tree) implementation
struct FenwickTree {
int size;
vector<long long> tree;
FenwickTree(int n) : size(n), tree(n + 1, 0) {}
void update(int idx, long long delta = 1) {
while (idx <= size) {
tree[idx] += delta;
idx += idx & (-idx);
}
}
// Query the prefix sum up to idx
long long query(int idx) const {
long long res = 0;
int i = idx;
while (i > 0) {
res += tree[i];
i -= i & (-i);
}
return res;
}
// Query the suffix sum from idx+1 to size
long long query_suffix(int idx) const {
return query(size) - query(idx);
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
// Read input
long long n, S;
// If reading from file, use freopen. Here we use standard input.
// freopen("CNTSEQ.INP", "r", stdin);
// freopen("CNTSEQ.OUT", "w", stdout);
cin >> n >> S;
vector<long long> A(n);
for(auto &x : A) cin >> x;
// Compute prefix sums
vector<long long> prefix(n + 1, 0);
for(int i =1;i<=n;i++) prefix[i] = prefix[i-1] + A[i-1];
// Collect all relevant values for coordinate compression
vector<long long> all_vals;
for(int i=0;i<=n;i++) {
all_vals.push_back(prefix[i]);
all_vals.push_back(prefix[i] - S);
all_vals.push_back(prefix[i] + S);
}
// Remove duplicates and sort
sort(all_vals.begin(), all_vals.end());
all_vals.erase(unique(all_vals.begin(), all_vals.end()), all_vals.end());
// Function to get the compressed index
auto get_idx = [&](long long x) -> int {
return lower_bound(all_vals.begin(), all_vals.end(), x) - all_vals.begin() +1;
};
// Count sum > S
FenwickTree ft1(all_vals.size());
long long count1 =0;
ft1.update(get_idx(prefix[0]));
for(int j=1;j<=n;j++) {
long long target = prefix[j] - S;
// Number of prefix[i-1] < target
// Which is number of prefix[i-1] <= target -1
// Since we have integers, but prefix can be any numbers, use lower_bound
// Number of prefix[i-1] < target is the index of first >= target
int pos = lower_bound(all_vals.begin(), all_vals.end(), target) - all_vals.begin();
count1 += ft1.query(pos);
ft1.update(get_idx(prefix[j]));
}
// Count sum < -S
FenwickTree ft2(all_vals.size());
long long count2 =0;
ft2.update(get_idx(prefix[0]));
for(int j=1;j<=n;j++) {
long long target = prefix[j] + S;
// Number of prefix[i-1] > target
// Which is total inserted so far minus number of prefix[i-1] <= target
int pos = upper_bound(all_vals.begin(), all_vals.end(), target) - all_vals.begin();
count2 += ft2.query(all_vals.size()) - ft2.query(pos);
ft2.update(get_idx(prefix[j]));
}
long long answer = count1 + count2;
// Output the answer
// cout << answer;
// If writing to file, use freopen. Here we use standard output.
// freopen("CNTSEQ.OUT", "w", stdout);
cout << answer;
}
How to Use the Code
-
Input File (CNTSEQ.INP):
- The first line contains two integers ( n ) and ( S ).
- The second line contains ( n ) integers representing the array ( A ).
-
Output File (CNTSEQ.OUT):
- The program outputs a single integer representing the number of contiguous subsequences where the absolute sum is greater than ( S ).
-
Running the Program:
- Ensure that the input is correctly placed in
CNTSEQ.INP.
- Compile and run the program in an environment that supports file I/O or modify the code to read from standard input and write to standard output as shown.
Example
Input (CNTSEQ.INP):
5 3
1 -2 3 -4 5
Output (CNTSEQ.OUT):
4
Explanation:
The contiguous subsequences with absolute sums greater than 3 are:
- [1, -2, 3] → Sum = 2
- [3] → Sum = 3
- [-2, 3, -4] → Sum = -3
- [3, -4, 5] → Sum = 4
Only the last subsequence has an absolute sum greater than 3.
Conclusion
This solution efficiently calculates the required number of subarrays using prefix sums and Fenwick Trees, achieving a time complexity of ( O(n \log n) ), which is suitable for large input sizes (( n \leq 10^5 )).