Cod sursa(job #2017171)

Utilizator LucaSeriSeritan Luca LucaSeri Data 31 august 2017 13:53:05
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.82 kb
#include <fstream>
#include <cassert>
#include <vector>
using namespace std;

ifstream cin("deque.in");
ofstream cout("deque.out");

class Deque{
public:
    long long Solve(int n, int k, vector <int> v){
        long long ans = 0;
        for(int i = 0; i < k; ++i){
            if(this -> size() == 0){
                this -> push_front(i);
            }
            else{
                while(this -> empty() == false && v[i] < v[this -> back -> val]) this -> pop_back();
                this -> push_back(i);
            }
        }
        ans += v[this -> front -> val];

        for(int i = k; i < n; ++i){
            while(this -> empty() == false && v[i] < v[this -> back -> val]) this -> pop_back();
            this -> push_back(i);
            while(this -> empty() == false && this -> front -> val <= i - k) this -> pop_front();
            ans += v[this -> front -> val];
        }

        return ans;
    }

private:
    int  sz = 0;
    struct Node{
        Node(int x){
            this -> val = x;
            this -> next = NULL;
            this -> prev = NULL;
        }

        int val;
        Node* next;
        Node* prev;
    };

    Node *back = NULL;
    Node *front = NULL;

    void push_front(int val){
        if(sz == 0){
            Node* n = new Node(val);
            back = n;
            front = n;
            ++sz;
        }
        else{
            Node* n = new Node(val);
            front -> next = n;
            n -> prev = front;
            front = n;
            ++sz;
        }
    }

    void push_back(int val){
        if(sz == 0){
            Node* n = new Node(val);
            back = n;
            front = n;
            ++sz;
        }
        else{
            Node* n = new Node(val);
            back -> prev = n;
            n -> next = back;
            back = n;
            ++sz;
        }
    }


    void pop_front(){
        assert(sz > 0);
        if(sz == 1){
            sz = 0;
            back = NULL;
            front = NULL;
        }
        else {
            --sz;
            front = front -> prev;
            delete(front -> next);
            front -> next = NULL;
        }

    }

    void pop_back(){
        assert(sz > 0);
        if(sz == 1){
            sz = 0;
            back = NULL;
            front = NULL;
        }
        else{
            -- sz;
            back = back -> next;
            delete(back -> prev);
            back -> prev = NULL;
        }
    }

    int size(){
        return sz;
    }

    bool empty(){
        return sz == 0;
    }
}deq;

int main(){
    int n;
    int k;
    cin >> n >> k;
    vector <int> v(n+1);
    for(int i = 0; i < n; ++i){
        cin >> v[i];
    }

    cout << deq.Solve(n, k, v);
    return 0;
}