Cod sursa(job #3122240)

Utilizator daristyleBejan Darius-Ramon daristyle Data 18 aprilie 2023 12:05:59
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>

using namespace std;

ifstream fin("deque.in");
ofstream fout("deque.out");

class deque {
private:
		static const int QUEUE_DIM = 8388608;
		int dq[QUEUE_DIM];
		int dqbp, dqep;
public:
		deque() {
			dqbp = dqep = 0;
		}

		inline void init() {
			dqbp = dqep = 0;
		}

		inline void push_back(int x) {
			dq[dqep++] = x;
			dqep &= (QUEUE_DIM - 1);
		}

		inline void push_front(int x) {
			dq[dqbp--] = x;
			dqbp = (dqbp + QUEUE_DIM) & (QUEUE_DIM - 1);
		}

		inline void pop_back() {
			dqep = (dqep + QUEUE_DIM - 1) & (QUEUE_DIM - 1);
		}

		inline void pop_front() {
			dqbp = (dqbp + 1) & (QUEUE_DIM - 1);
		}

		inline int back() {
			return dq[(dqep + QUEUE_DIM - 1) & (QUEUE_DIM - 1)];
		}

		inline int front() {
			return dq[dqbp];
		}

		inline bool empty() {
			return dqbp == dqep;
		}

		inline void clear() {
			init();
		}

		void print() {
			int i = dqbp;
			while(i != dqep){
				fout << dq[i] << ' ';
				i = (i + 1) & (QUEUE_DIM - 1);
			}

			fout.put('\n');
		}
};

const int K_MAX = 5e6;
int v[K_MAX];
deque dq;

int main() {
	dq.init();

	int n, k;
	fin >> n >> k;
	for(int i = 0; i < k - 1; ++i){
		fin >> v[i];
		while(!dq.empty() && dq.back() > v[i])
			dq.pop_back();
		dq.push_back(v[i]);
	}

	long long sum = 0;
	for(int ii = k - 1; ii < n; ++ii){
		int i = ii % k;
		fin >> v[i];

		while(!dq.empty() && dq.back() > v[i])
			dq.pop_back();
		dq.push_back(v[i]);

		sum += dq.front();

		if(v[(ii - k + 1) % k] == dq.front())
			dq.pop_front();
	}

	fout << sum << '\n';

	fin.close();
	fout.close();
	return 0;
}