Cod sursa(job #983690)

Utilizator cosmo0093Raduta Cosmin cosmo0093 Data 12 august 2013 15:52:56
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>

class Deque
{
	
	struct Node
	{
		int data;
		Node *next;
		Node *prev;
	};
	Node *start, *end;
	
	
public:
	
	Deque() : start(NULL), end(NULL) { }
	
	~Deque()
	{
		while(start != NULL)
		{
			pop_back();
		}
	}
	
	bool empty()
	{
		if(start == NULL) return true;
		return false;
	}
	
	void push_front(int key)
	{
		if(start == NULL)
		{
			Node *c = new Node();
			c->data = key;
			start = end = c;
		}
		else
		{
			Node *c = new Node();
			c->data = key;
			c->next = start;
			start->prev = c;
			start = c;
		}
	}
	
	void push_back(int key)
	{
		if(end == NULL)
		{
			Node *c = new Node();
			c->data = key;
			start = end = c;
		}
		else
		{
			Node *c = new Node();
			c->data = key;
			c->prev = end;
			end->next = c;
			end = c;
		}
	}
	
	long long front()
	{
		if(start != NULL) return start->data;
		return 0;
	}
	
	long long back()
	{
		if(start != NULL) return end->data;
		return 0;
	}
	
	void pop_front()
	{
		Node *c = start;
		if(start->next == NULL)
		{
			start = end = NULL;
		}
		else
		{
			start = start->next;
			start->prev = NULL;
		}
		delete c;
	}
	
	void pop_back()
	{
		Node *c = end;
		if(end->prev == NULL)
		{
			start = end = NULL;
		}
		else
		{
			end = end->prev;
			end->next = NULL;
		}
		delete c;
	}
};

int main()
{
	std::ifstream in("deque.in");
	std::ofstream out("deque.out");
	Deque myDeq;
	int nV;
	int k;
	in >> nV >> k;
	int *nArr = new int[nV + 1];
	for(int i = 1; i <= nV; i++)
		in >> nArr[i];
	long long sum = 0;
	for(int i = 1; i <= nV; i++)
	{
		while(myDeq.front() <= i - k && !myDeq.empty())
			myDeq.pop_front();
		
		while(nArr[myDeq.back()] >= nArr[i] && !myDeq.empty())
			myDeq.pop_back();
			
		myDeq.push_back(i);
		
		if(i >= k) 
			sum += nArr[myDeq.front()];
	}
	out << sum;
	return 0;
}