Cod sursa(job #2726227)

Utilizator GhiuzanuEdward Ghiuzan Ghiuzanu Data 20 martie 2021 15:10:26
Problema Deque Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#define maxn 5000010
using namespace std;

int N, K, L;
int A[maxn];
long long Sum;
int H[maxn], P[maxn];

void push(int x)
{
    int aux;
    while (x / 2 >= 1 && A[H[x]] < A[H[x / 2]])
    {
        aux = H[x];
        H[x] = H[x / 2];
        H[x / 2] = aux;
        P[H[x]] = x;
        P[H[x / 2]] = x / 2;
        x = x / 2;
    }
}
void pop(int x)
{
    int aux, y = 0;

    while (x != y)
    {
        y = x;
        if (y * 2 <= L && A[H[x]] > A[H[y * 2]])
            x = y * 2;
        if (y * 2 + 1 <= L && A[H[x]] > A[H[y * 2 + 1]])
            x = y * 2 + 1;
        aux = H[x];
        H[x] = H[y];
        H[y] = aux;
        P[H[x]] = x;
        P[H[y]] = y;
    }
}
int main() {
    ifstream fin("deque.in");
    ofstream fout("deque.out");
    fin>>N>>K;
    int i;
    for (i = 1; i <= N; ++i) {
        fin>>A[i];
        L++;
        H[L] = i;
        P[H[L]] = L;
        push(L);
        while (H[1] <= i-K)
        {
            H[1] = H[L--];
            P[H[1]] = 1;
            pop(1);
        }
        if (i >= K)
            Sum = Sum + A[H[1]];
    }
    fout<<Sum;
    fin.close();
    fout.close();
    return 0;
}