Cod sursa(job #1860017)

Utilizator jason2013Andronache Riccardo jason2013 Data 27 ianuarie 2017 21:01:01
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<bits/stdc++.h>
#define NMAX 5000000
using namespace std;

int N, K, L;
int a[NMAX], h[NMAX], p[NMAX];
long long Sum;

inline int father(int child)
{return child/2;}

inline int left_son(int father)
{return father*2;}

inline int right_son(int father)
{return father*2+1;}

int swap_h(int x, int y)
{
    int aux;
    aux = h[x]; h[x] = h[y]; h[y] = aux;
}

void percolate(int nod)
{
    while(father(nod) >= 1 && a[h[nod]] < a[h[father(nod)]])
    {
        swap_h(nod, father(nod));
        p[h[nod]] = nod;
        p[h[father(nod)]] = father(nod);
        nod = father(nod);
    }
}

void sift(int nod)
{
    int son = 0;
    while(son != nod)
    {
        son = nod;
        if(left_son(son) <= L && a[h[left_son(son)]] < a[h[nod]] ) nod = left_son(son);
        if(right_son(son) <= L && a[h[right_son(son)]] < a[h[nod]] ) nod = right_son(son);

        swap_h(nod, son);
        p[h[son]] = son;
        p[h[nod]] = nod;

    }
}

int main()
{
    freopen("deque.in", "r", stdin);
    freopen("deque.out", "w", stdout);

    scanf("%d %d ", &N, &K);

    int i;

    for (i = 1; i <= N; i++)
    {
        scanf("%d ", &a[i]);

        L++;
        h[L] = i;
        p[h[L]] = L;
        percolate(L);

        while (h[1] <= i-K)
        {
            h[1] = h[L--];
            p[h[1]] = 1;
            sift(1);
        }

        if (i >= K)  Sum += a[h[1]];
    }

    printf("%lld", Sum);

    return 0;
}