#include #include #include constexpr size_t MAX_N = 1e6 + 1; constexpr unsigned long long SOLVE_1_THRESHOLD = 0; template class QueueWithMinMax { protected: std::deque max_queue, min_queue; // std::priority_queue, std::greater<>> min_queue; public: std::queue q; void push(const T& x) { q.push(x); while (!max_queue.empty() && max_queue.back() < x) { max_queue.pop_back(); } max_queue.push_back(x); while (!min_queue.empty() && min_queue.back() > x) { min_queue.pop_back(); } min_queue.push_back(x); } void pop() { if (!max_queue.empty() && q.front() >= max_queue.front()) { max_queue.pop_front(); } if (!min_queue.empty() && q.front() <= min_queue.front()) { min_queue.pop_front(); } q.pop(); } [[nodiscard]] T front() const { return q.front(); } [[nodiscard]] T get_max() const { return max_queue.front(); } [[nodiscard]] T get_min() const { return min_queue.front(); } }; int n, window_length; int nums[MAX_N], max_nums[MAX_N], min_nums[MAX_N]; QueueWithMinMax queue; void solve_1() { for (int i = 0; i + window_length <= n; i++) { max_nums[i] = *std::max_element(nums + i, nums + i + window_length); min_nums[i] = *std::min_element(nums + i, nums + i + window_length); } } void solve_2() { for (int i = 0; i < window_length; i++) { queue.push(nums[i]); } for (int i = 0; i + window_length < n; i++) { max_nums[i] = queue.get_max(); min_nums[i] = queue.get_min(); queue.pop(); queue.push(nums[i + window_length]); } max_nums[n - window_length] = queue.get_max(); min_nums[n - window_length] = queue.get_min(); } void print_ans() { for (int i = 0; i <= n - window_length; i++) { std::cout << min_nums[i] << " "; } std::cout << std::endl; for (int i = 0; i <= n - window_length; i++) { std::cout << max_nums[i] << " "; } std::cout << std::endl; } int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cin >> n >> window_length; if (window_length > n) { window_length = n; } for (int i = 0; i < n; i++) { std::cin >> nums[i]; } if (1ll * n * window_length < SOLVE_1_THRESHOLD) { solve_1(); } else { solve_2(); } // solve_1(); // print_ans(); // solve_2(); print_ans(); return 0; }