Cod sursa(job #2887298)

Utilizator widzAndrei-Daniel Tava widz Data 9 aprilie 2022 12:31:40
Problema Deque Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <iostream>
#include <fstream>
using namespace std;

template <class Type>
class Deque
{
private:
	Type* storage;
	int max_size,front,back;
public:
	Deque(int size)
	{
		max_size = size;
		storage = new Type[max_size];
		back = max_size / 2;
		front = max_size / 2 - 1;
	}
	~Deque()
	{
		delete[] storage;
	}
	void push_front(Type nr)
	{
		if(front < max_size - 1)
			storage[++front] = nr;
	}
	void push_back(Type nr)
	{
		if (back > 0)
			storage[--back] = nr;
	}
	Type peek_front()
	{
		if (front < max_size - 1)
			return storage[front];
		return Type();
	}
	Type peek_back()
	{
		if (back > 0)
			return storage[back];
		return Type();
	}
	void pop_front()
	{
		if (!empty())
			--front;
	}
	void pop_back()
	{
		if (!empty())
			++back;
	}
	bool empty()
	{
		if (front < back)
			return 1;
		return 0;
	}
};

struct pereche
{
	int first, second;
	pereche() : first(0), second(0) {};
	pereche(int f, int s) : first(f), second(s){};
};

int main()
{
	ifstream in("deque.in");
	ofstream out("deque.out");
	int n, k, nr;
	long long sum = 0;
	in >> n >> k;
	Deque<pereche> mins(10000000);
	for(int i=0; i<n; ++i)
	{
		in >> nr;
		while (!mins.empty() && nr < mins.peek_front().second)
			mins.pop_front();
		pereche ind_nr(i, nr);
		mins.push_front(ind_nr);
		if (mins.peek_back().first <= i - k)
			mins.pop_back();
		if(i>=k - 1)
			sum += mins.peek_back().second;
	}
	in.close();
	out << sum;
	out.close();
}