Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <algorithm>
- #include <vector>
- #include <cmath>
- #include <set>
- #include <array>
- using namespace std;
- const int maxn = 2e5 + 10;
- typedef long long ll;
- multiset<int> smaller_values, greater_values;
- int k;
- void insert_value(int x, ll & difference_smaller, ll & sum_greater) {
- int max_in_smaller = *smaller_values.rbegin();
- if(max_in_smaller < x) {
- greater_values.insert(x);
- sum_greater += x;
- if(greater_values.size() > k / 2) {
- int min_in_greater = *greater_values.begin();
- smaller_values.insert(min_in_greater);
- greater_values.erase(greater_values.find(min_in_greater));
- sum_greater -= min_in_greater;
- difference_smaller -= min_in_greater;
- }
- }
- else {
- smaller_values.insert(x);
- difference_smaller -= x;
- if(smaller_values.size() > (k + 1) / 2) {
- int tmp_max_in_smaller = *smaller_values.rbegin();
- greater_values.insert(tmp_max_in_smaller);
- smaller_values.erase(smaller_values.find(tmp_max_in_smaller));
- difference_smaller += tmp_max_in_smaller;
- sum_greater += tmp_max_in_smaller;
- }
- }
- }
- void remove_value(int x, ll & difference_smaller, ll & sum_greater) {
- if(greater_values.find(x) != greater_values.end()) {
- greater_values.erase(greater_values.find(x));
- sum_greater -= x;
- }
- else if(smaller_values.find(x) != smaller_values.end()) {
- smaller_values.erase(smaller_values.find(x));
- difference_smaller += x;
- }
- if(smaller_values.empty()) {
- int tmp = *greater_values.begin();
- smaller_values.insert(*greater_values.begin());
- greater_values.erase(greater_values.begin());
- difference_smaller -= tmp;
- sum_greater -= tmp;
- }
- }
- int main() {
- ios_base::sync_with_stdio(false);
- int n;
- cin >> n >> k;
- vector<int> v(n);
- for(int i = 0; i < n; i++) {
- cin >> v[i];
- }
- smaller_values.insert(v[0]);
- ll difference_smaller = -v[0];
- ll sum_greater = 0;
- for(int i = 1; i < k; i++) {
- insert_value(v[i], difference_smaller, sum_greater);
- }
- ll median = *smaller_values.rbegin();
- ll tmp = (ll) (smaller_values.size() * median) + difference_smaller;
- tmp += sum_greater - (ll) (greater_values.size() * median);
- cout << tmp << " ";
- for(int i = k; i < n; i++) {
- if(k > 1) {
- remove_value(v[i - k], difference_smaller, sum_greater);
- insert_value(v[i], difference_smaller, sum_greater);
- }
- else {
- insert_value(v[i], difference_smaller, sum_greater);
- remove_value(v[i - 1], difference_smaller, sum_greater);
- }
- median = *smaller_values.rbegin();
- tmp = (ll) (smaller_values.size() * median) + difference_smaller;
- tmp += sum_greater - (ll) (greater_values.size() * median);
- cout << tmp << " ";
- }
- return 0;
- }
- // 5, 1, 2, 3
- // 1, 2, 3, 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement