PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#PS0000140. Đếm đoạn nhị phân có tổng cho trước (Binary Subarrays With Sum)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đếm đoạn nhị phân có tổng cho trước (Binary Subarrays With Sum)

Binary Subarrays With Sum

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given a binary array a1,…,ana_1,\ldots,a_n and an integer KK, count its nonempty contiguous subarrays whose element sum equals KK. Subarrays with different endpoint pairs are counted separately, even if their contents are identical.

Input

  • Line 1: integer nn, the array length and integer KK, the target sum.
  • Line 2: nn integers a1,…,ana_1,\ldots,a_n in order.

Output

Print the number of qualifying intervals, or 0 if there are none.

Subtasks

  • Subtask 1 (20 points): 1≤n≤10001\le n\le 1000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}; 0≤K≤n0\le K\le n.
  • Subtask 2 (30 points): 1≤n≤300001\le n\le 30000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}; 0≤K≤n0\le K\le n; K=0K=0.
  • Subtask 3 (50 points): 1≤n≤300001\le n\le 30000; 1≤i≤n1\le i\le n; ai∈{0,1}a_i\in\{0,1\}; 0≤K≤n0\le K\le n.

Example 1

Input

5 2
1 0 1 0 1

Output

4

Explanation

The four intervals [1,3][1,3], [1,4][1,4], [2,5][2,5], and [3,5][3,5] each contain exactly two ones; no other interval does.

Example 2

Input

5 0
0 0 0 0 0

Output

15

Explanation

All five entries are zero. Lengths 1 through 5 give 5, 4, 3, 2 and 1 intervals, totaling 15.