Cod sursa(job #2971990)

Utilizator Robert_MitriRobert Mitri Robert_Mitri Data 28 ianuarie 2023 14:42:54
Problema Deque Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb
#include <fstream>

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

int n;
int k;

long long s;

struct nod
{
    int val;
    nod *urm;
    nod *pred;
};

struct dq
{
    nod *head=NULL;
    nod *last=NULL;
    int back()
    {
        return last->val;
    }
    int front()
    {
        return head->val;
    }
    bool empty()
    {
        return head==NULL && last==NULL;
    }
    void push_fr(int value)
    {
        if (head==NULL)
        {
            nod *nw = new nod;
            head=nw;
            head->val=value;
            head->urm=NULL;
            head->pred=NULL;
            last=head;
            return;
        }
        nod *nw = new nod;
        nw->val=value;
        nw->urm=head;
        nw->pred=NULL;
        head=nw;

    }
    void push_bk(int value)
    {
         if (head==NULL)
        {
            nod *nw = new nod;
            head=nw;
            head->val=value;
            head->urm=NULL;
            head->pred=NULL;
            last=head;
            return;
        }
        nod *nw = new nod;
        last->urm=nw;
        nw->val=value;
        nw->pred=last;
        nw->urm=NULL;
        last=nw;

    }
    void pop_fr()
    {
        if(head==last)
        {
            head=NULL;
            last=NULL;
            head->urm=NULL;
            head->pred=NULL;
            last->urm=NULL;
            last->pred=NULL;
            return;
        }
        head=head->urm;
        delete head->pred;
        head->pred=NULL;
    }
    void pop_bk()
    {
        if(head==last)
        {
            head=NULL;
            last=NULL;
            return;
        }
        last=last->pred;
        delete last->urm;
        last->urm=NULL;
    }
    void afis()
    {
        if (empty())
            return;
        nod *p = new nod;
        p=head;
        while(p->urm!=NULL)
        {
            fout<<p->val<<' ';
            p=p->urm;
        }
        fout<<p->val<<' ';
    }


} q;
int v[5000001];


int main()
{
    fin>>n>>k;
    for(int i=1;i<k;i++)
    {
        fin>>v[i];
        while(q.empty()==false && v[i]<=v[q.back()])
        {
            q.pop_bk();
        }
        q.push_bk(i);
    }
    for(int i=k;i<=n;i++)
    {
        fin>>v[i];
        while(q.empty()==false && v[i]<=v[q.back()])
        {
            q.pop_bk();
        }
        while(q.empty()==false && i-q.front()+1>k){
            q.pop_fr();
        }

        q.push_bk(i);
        s+=v[q.front()];
    }
    fout<<s;
}