Cod sursa(job #1058683)

Utilizator rcalitaCalita Raluca rcalita Data 15 decembrie 2013 19:41:52
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
ifstream f("deque.in");
ofstream g("deque.out");
int i,n,k,v[5000001],heap[5000001],a[5000001],l;
long long suma;
void inserare(int x)
{
    while (x/2>=1 && v[heap[x]] < v[heap[x/2]])
    {
        swap(heap[x],heap[x/2]);
        a[heap[x]] = x;
        a[heap[x/2]] = x/2;
        x /= 2;
    }
}
void pop(int x)
{
    int y = 0;
    while (x != y)
    {
        y = x;
        if (y*2<=l && v[heap[x]]>v[heap[y*2]])
            x = y*2;
        if (y*2+1<=l && v[heap[x]]>v[heap[y*2+1]])
            x = y*2+1;
        swap(heap[x],heap[y]);
        a[heap[x]] = x;
        a[heap[y]] = y;
    }
}
int main()
{
    f>>n>>k;
    for(i=1;i<=n;i++)
    {
        f>>v[i];
        l++;
        heap[l] = i;
        a[heap[l]]=l;
        inserare(l);
        while (heap[1] <= i-k)
        {
            heap[1] = heap[l--];
            a[heap[1]] = 1;
            pop(1);
        }

        if (i >= k)
            suma += v[heap[1]];
    }
    g<<suma;
    return 0;
}