CSES - Sliding Cost
Author: Isaac Noel
Time Complexity:
Abstract
Finding the difference between sums of the upper elements and lower with two multisets.
Warning!
The implementation of this solution assumes familarity with Sliding Median as their implementations are near identical.
Solution
The cost of a window
It can be shown that it is optimal to change the values of the window to the median (left as an exercise :D). Once we find the median, we must find the sum of the distances of all elements to the median. Summing the distances for each element individually is too slow. Instead, we'll split the elements in the window into two groups and calculate the cost as described below. The smallest elements in the window will be in the lower group while the largest elements in the window will be in the upper group.
The cost of the window can be expressed as a function of , and , where and denote the sum of elements in the lower and upper group respectively, and denotes the median of the window. The cost of the lower group will be , and the cost of the upper group will be , where represents an element in the group. These expressions can be simplified to and . The total cost of the window is the sum of the costs contributed by both groups, or .
Implementation
Finding the difference between the largest elements in the window and the smallest elements in the window is similar to finding the sliding median (more info here). To maintain the current cost, we keep track of the sum of each multiset as we insert and erase. Using the double multiset method described in the Sliding Median solution, we let the lower group include the lower elements in the window. As a result, when the window size is odd, the lower group has one more than element than the desired amount. We can correct for this by adding the median to the final answer if the window size is odd.
#include <algorithm>#include <iostream>#include <set>using namespace std;using ll = long long;const ll mn = (ll)2e5 + 5;ll N, K;ll arr[mn];multiset<ll> up;
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!