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

#FT0000039. Trung vị cửa sổ trượt (Sliding Window Median)

HỌC THEO LỘ TRÌNH

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

2 lộ trình

Trung vị cửa sổ trượt (Sliding Window Median)

Sliding Window Median

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

Given integers x1,x2,…,xnx_1,x_2,\ldots,x_n and window length kk, consider all contiguous windows of exactly kk elements, starting at positions 11 through n−k+1n-k+1.

To define a window median, sort its kk values in nondecreasing order. For odd kk, take the middle element. For even kk, take the smaller of the two middle elements (the element of rank k/2k/2, counting from 11). Equal values remain separate occurrences.

Output each window median from left to right.

Input

  • Line 1: integers n,kn,k, array length and window length.
  • Line 2: nn integers x1,x2,…,xnx_1,x_2,\ldots,x_n.

Output

Print n−k+1n-k+1 integers on one line: the window medians, from left to right.

Subtasks

Subtask 1 (20 points):

  • 1≤k≤n≤201\le k\le n\le 20; 1≤xi≤1091\le x_i\le 10^9 for every 1≤i≤n1\le i\le n.

Subtask 2 (30 points):

  • 1≤k≤n≤20001\le k\le n\le 2000; 1≤xi≤1091\le x_i\le 10^9 for every 1≤i≤n1\le i\le n.

Subtask 3 (50 points):

  • 1≤k≤n≤2000001\le k\le n\le 200000; 1≤xi≤1091\le x_i\le 10^9 for every 1≤i≤n1\le i\le n.

Examples

Examples 1

Input

8 3
2 4 3 5 8 1 2 1

Output

3 4 5 5 2 1

Explanation

The six sorted windows are [2,3,4][2,3,4], [3,4,5][3,4,5], [3,5,8][3,5,8], [1,5,8][1,5,8], [1,2,8][1,2,8], [1,1,2][1,1,2]. Their middle values are respectively 3,4,5,5,2,13,4,5,5,2,1.

Examples 2

Input

4 2
9 2 6 2

Output

2 2 2

Explanation

With window size 22, choose the smaller value in each pair: min⁡(9,2)=2\min(9,2)=2, min⁡(2,6)=2\min(2,6)=2, and min⁡(6,2)=2\min(6,2)=2.

The three windows are [9,2][9,2], [2,6][2,6], and [6,2][6,2]. Their sorted forms are [2,9][2,9], [2,6][2,6], and [2,6][2,6]. For even kk, the task requires the lower median, which is the first element of each sorted pair; all three outputs are therefore 22.