Cod sursa(job #2620366)

Utilizator AlexVulpoiuAlexandru Vulpoiu AlexVulpoiu Data 28 mai 2020 19:40:51
Problema Deque Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>

using namespace std;

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

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

struct coada_dubla
{
    nod *p, *u;
};

int n, k, i, x;
long long int s;
coada_dubla dq1, dq2;

bool goala(const coada_dubla& cd)
{
    return cd.p == NULL;
}

void adauga_spate(coada_dubla& cd, const int& x)
{
    nod *aux = new nod;

    if(cd.u == NULL)
    {
        aux->val = x;
        aux->urm = NULL;
        cd.p = cd.u = aux;
    }
    else
    {
        aux->val = x;
        aux->urm = NULL;
        cd.u->urm = aux;
        cd.u = aux;
    }
}

void sterge_fata(coada_dubla& cd)
{
    if(cd.p == cd.u)
    {
        cd.p = cd.u = NULL;
        return;
    }
    cd.p = cd.p->urm;
}

void sterge_spate(coada_dubla& cd)
{
    nod *it;

    if(cd.p == cd.u)
    {
        cd.p = cd.u = NULL;
        return;
    }

    for(it = cd.p; it != NULL; it = it->urm)
        if(it->urm == cd.u)
        {
            it->urm = NULL;
            cd.u = it;
            break;
        }
}

int main()
{
    s = 0;

    f >> n >> k;
    for(i = 1; i <= n; i++)
    {
        f >> x;

        while(!goala(dq1) && dq1.u->val > x)
        {
            sterge_spate(dq1);
            sterge_spate(dq2);
        }
        adauga_spate(dq1, x);
        adauga_spate(dq2, i);
        while(!goala(dq2) && dq2.p->val <= i - k)
        {
            sterge_fata(dq2);
            sterge_fata(dq1);
        }
        if(i >= k)
            s += dq1.p->val;
    }

    g << s << "\n";

    f.close();
    g.close();

    return 0;
}