#C6350. Count Contiguous Subarrays with Target Sum

    ID: 50101 Type: Default 1000ms 256MiB

Count Contiguous Subarrays with Target Sum

Count Contiguous Subarrays with Target Sum

You are given an array A of N integers and an integer M. Your task is to determine the number of contiguous subarrays (segments) of A whose elements sum exactly to M. This problem can be solved efficiently using the prefix sum technique, which reduces the time complexity to O(N) on average.

Let \( prefix[i] \) denote the sum of the first \( i \) elements of \( A \). The key observation is that the sum of the subarray from index \( i+1 \) to \( j \) is \( prefix[j] - prefix[i] \). Thus, for each index \( j \), if we know how many indices \( i \) (with \( i < j \)) satisfy \( prefix[j] - prefix[i] = M \), we can accumulate the answer.

Your program should read the input from standard input (stdin) and output the result to standard output (stdout).

inputFormat

The first line of the input contains two space-separated integers \( N \) and \( M \), where \( N \) is the number of elements in the array and \( M \) is the target sum.

The second line contains \( N \) space-separated integers representing the array A.

outputFormat

Output a single integer representing the number of contiguous subarrays that sum exactly to \( M \).

## sample
5 5
1 2 3 2 1
2