Cod sursa(job #3127384)

Utilizator willOcanaru Mihai will Data 7 mai 2023 15:05:40
Problema Deque Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stdexcept>

using namespace std;

ifstream f("deque.in");
ofstream g("deque.out");


#define MAX_SIZE  5000000

using namespace std;

template <typename T>
class Deque {
private:
    T* data;
    size_t front_index;
    size_t back_index;
    size_t capacity;

public:
    Deque(int n) {
        capacity = n + 4;
        front_index = capacity / 2;
        back_index = (capacity / 2) + 1;
        data = new T[capacity](); // initialize elements to default value
    }

    ~Deque() {
        delete[] data;
    }

    void push_front(T x) {
        if (front_index == 0) {
            throw std::runtime_error("Deque is full");
        }
        data[--front_index] = x;
    }

    void push_back(T x) {
        if (back_index == capacity - 1) {
            throw std::runtime_error("Deque is full");
        }
        data[back_index++] = x;
    }

    void pop_front() {
        if (empty()) {
            throw std::runtime_error("Deque is empty");
        }
        ++front_index;
    }

    void pop_back() {
        if (empty()) {
            throw std::runtime_error("Deque is empty");
        }
        --back_index;
    }

    T& front() {
        if (empty()) {
            throw std::runtime_error("Deque is empty");
        }
        return data[front_index];
    }

    T& back() {
        if (empty()) {
            throw std::runtime_error("Deque is empty");
        }
        return data[back_index - 1];
    }

    bool empty() const {
        return size() == 0;
    }

    size_t size() const {
        return back_index - front_index;
    }
};

void display(Deque<pair<long long, long long>> deque){
    while(!deque.empty()){
        cout << deque.front().first << " ";
        deque.pop_front();
    }
    cout << endl;
}

int main()
{

    // vector<int> elements;
	

    long long no_of_elements, interval, x, sum = 0, last;
    f >> no_of_elements >> interval;

    Deque<pair<long long, long long>> deque(no_of_elements);
    // for(long long i=0; i<no_of_elements; i++){
    //     f >> x;
	// 	elements[index ++] = x;
    // }

    for(long long i=0; i<no_of_elements; i++){

		f >> x;

        while(!deque.empty() && x <= deque.back().first){
            deque.pop_back();    
        }

        deque.push_back({x, i});

        if(deque.front().second <= i - interval) deque.pop_front();

        if(i >= interval - 1){ 
            sum += deque.front().first;
         }
    }

    g << sum;	

    return 0;
}