Cod sursa(job #2981358)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 17 februarie 2023 20:00:30
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <cstdio>
#include <memory>
#include <queue>
#include <vector>

using namespace std;

class Solver{
private:
public:
  Solver() {
    freopen("deque.in", "r", stdin);
    freopen("deque.out", "w", stdout);
  }
  ~Solver() {
    fclose(stdin);
    fclose(stdout);
  }
  void execute() {
    deque<int> dq;
    // dq.back() - the index of the smallest value in the last K values
    // dq[i] contains the indices in values in decreasing order
    // values[dq[i]] contains the smallest K values in decreasing order
    int N, K;
    scanf("%d%d", &N, &K);
    vector<int> values(N);

    long long total = 0;
    
    for (int i = 0; i < N; ++i) {
      scanf("%d", &values[i]);

      while (!dq.empty() && values[dq.front()] >= values[i])
	dq.pop_front();
      dq.push_front(i);
      
      if (!dq.empty() && i - dq.back() == K)
	dq.pop_back();

      if (i >= K - 1)
	total += values[dq.back()];
    }
    printf("%lld\n", total);
    
  }
};

int main() {
  unique_ptr<Solver> s = make_unique<Solver>();
  s->execute();
  return 0;
}