Cod sursa(job #2888294)

Utilizator stefanliciuLiciu Vasile-Stefan stefanliciu Data 10 aprilie 2022 22:04:18
Problema Deque Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>

using namespace std;

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

class Deque {
	int left_index;
	int right_index;
	int* v;
public:
	Deque(int n, int left = 0, int right = -1) { v = new int[n]; this->left_index = left; this->right_index = right; }
	~Deque() { delete[] v; }
	bool empty();
	void push_back(int x);
	void push_front(int x);
	void pop_back();
	void pop_front();
	void afis();
	int back();
	int front();
	int get_right_index();
	int get_left_index();
	int& operator[] (int);
};

int Deque::get_left_index()
{
	return left_index;
}
int Deque::get_right_index()
{
	return right_index;
}
int Deque::back()
{
	return v[right_index];
}
int Deque::front()
{
	return v[left_index];
}
int& Deque::operator[](int index)
{
	if (index > right_index)
	{
		cout << "Index out of bound\n";
		cout << "Indexul este: " << index <<"si right index este: "<<right_index << endl;
		exit(0);
	}
	return v[index];

}
void Deque::afis()
{
	for (int i = left_index; i < right_index; ++i)
		cout << v[i] << ' ';
}
bool Deque::empty()
{
	return (left_index > right_index);
}

void Deque::push_back(int x)
{
	v[++right_index] = x;
}

void Deque::push_front(int x)
{
	right_index++;
	
	for (int i = right_index; i > left_index; i--)
	{
		v[i] = v[i - 1];
	}
	
	v[left_index] = x;
}

void Deque::pop_back()
{
	if (!this->empty())
		right_index--;
	else
		cout << "Coada este goala";
}
void Deque::pop_front()
{  if(!this->empty())
	left_index++;
}

int main()
{
	int N, K, x;
	long long suma = 0;
	fin>> N >> K;
	Deque Deck(N + 1);
	int* arr = new int[N + 1];
	for (int i = 0; i < N; ++i)
	{
		fin >> arr[i];
		
		while (!Deck.empty() && arr[i] <= arr[Deck[Deck.get_right_index()]])
			Deck.pop_back();
		
		Deck.push_back(i);
		if (Deck[Deck.get_left_index()] + K == i)
			Deck.pop_front();
		if(i >= K - 1)
	     suma += arr[Deck[Deck.get_left_index()]];
	}
	cout << suma;
}