結果
| 問題 | No.738 平らな農地 | 
| コンテスト | |
| ユーザー |  ei1333333 | 
| 提出日時 | 2018-09-28 22:23:43 | 
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) | 
| 結果 | 
                                AC
                                 
                             | 
| 実行時間 | 370 ms / 2,000 ms | 
| コード長 | 2,345 bytes | 
| コンパイル時間 | 2,309 ms | 
| コンパイル使用メモリ | 211,684 KB | 
| 最終ジャッジ日時 | 2025-01-06 13:55:06 | 
| ジャッジサーバーID (参考情報) | judge1 / judge3 | 
(要ログイン)
| ファイルパターン | 結果 | 
|---|---|
| sample | AC * 5 | 
| other | AC * 87 | 
ソースコード
#include <bits/stdc++.h>
using namespace std;
using int64 = long long;
template< typename T >
struct PrioritySumStructure {
  static const bool INCREASE = false;
  static const bool DECREASE = true;
  bool order;
  int k, sz;
  T sum;
  set< pair< T, int > > add, pend;
  map< int, T > adding, pending;
  PrioritySumStructure(int k, bool order = INCREASE) : k(k), sum(0), sz(0), order(order) {}
  void Sweep() {
    while(sz < k && !pend.empty()) {
      auto p = order ? --pend.end() : pend.begin();
      sum += p->first;
      ++sz;
      add.emplace(*p);
      adding.emplace(p->second, p->first);
      pending.erase(p->second);
      pend.erase(p);
    }
    while(sz > k) {
      auto p = order ? add.begin() : --add.end();
      sum -= p->first;
      --sz;
      pend.emplace(*p);
      pending.emplace(p->second, p->first);
      adding.erase(p->second);
      add.erase(p);
    }
  }
  T getSum() {
    if(sz < k) throw ("get Sum Exception");
    return (sum);
  }
  void addElement(int k, T x) {
    if(adding.count(k) || pending.count(k)) {
      throw ("Add Element Exception");
    }
    ++sz;
    add.emplace(x, k);
    adding[k] = x;
    sum += x;
    Sweep();
  }
  void deleteElement(int k) {
    if(pending.count(k)) {
      pend.erase({pending[k], k});
      pending.erase(k);
    } else if(adding.count(k)) {
      --sz;
      sum -= adding[k];
      add.erase({adding[k], k});
      adding.erase(k);
      Sweep();
    } else {
      throw ("delete Element Exception");
    }
  }
  void incrementSize() {
    ++k;
    Sweep();
  }
  void decrementSize() {
    if(k == 0) throw ("decrement Size Exception");
    --k;
    Sweep();
  }
};
using int64 = long long;
const int64 INF = 1LL << 60;
int main() {
  int N, K, A[100000];
  cin >> N >> K;
  for(int i = 0; i < N; i++) cin >> A[i];
  int64 all[100001] = {};
  for(int i = 1; i <= N; i++) all[i] = A[i - 1] + all[i - 1];
  int sz = (K + 1) / 2;
  PrioritySumStructure< int64 > que(sz, false);
  int64 ret = 1LL << 60;
  for(int i = 0; i < N; i++) {
    que.addElement(i, A[i]);
    if(i - K + 1 >= 0) {
      int64 sum = all[i + 1] - all[i - K + 1];
      auto cand = prev(que.add.end())->first;
      ret = min(ret, cand * sz - que.getSum() + (sum - que.getSum()) - (K - sz) * cand);
      que.deleteElement(i - K + 1);
    }
  }
  cout << ret << endl;
}
            
            
            
        