#C9151. Count Subarrays with a Given Sum
Count Subarrays with a Given Sum
Count Subarrays with a Given Sum
You are given an array of integers and a target integer \(X\). Your task is to determine the number of contiguous subarrays whose sum is equal to \(X\). This problem requires careful handling of the cumulative sum and efficient counting of the number of times a particular cumulative sum has occurred.
The problem can be formulated as follows:
Given an array \(a[0 \dots n-1]\) and an integer \(X\), find the number of pairs of indices \((i, j)\) (with \(0 \leq i \leq j < n\)) such that \[ \sum_{k=i}^{j} a[k] = X. \]
Efficient solutions often employ prefix sums along with a hash table to store the frequency of prefix sums encountered so far.
inputFormat
The input is read from standard input (stdin) and consists of two lines:
- The first line contains two integers \(n\) and \(X\), where \(n\) is the number of elements in the array and \(X\) is the target sum.
- The second line contains \(n\) integers representing the elements of the array.
If \(n = 0\), the second line will be empty.
outputFormat
Output a single integer representing the number of contiguous subarrays whose sum is exactly \(X\). The output should be written to standard output (stdout).
## sample5 3
1 2 1 2 1
4