Cod sursa(job #823617)

Utilizator IoannaPandele Ioana Ioanna Data 25 noiembrie 2012 13:07:39
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include<fstream>
#include<vector>
#define NMAX 5000001
using namespace std;

int N,K;
long long suma;

struct heap
{
    int x,poz;
};

heap h[NMAX];
ifstream in("deque.in");
ofstream out("deque.out");

void scan()
{
    in>>N>>K;
}

void addToHeap(int p)
{
    heap aux;
    if (p/2==0)
        return;
    if (h[p].x<h[p/2].x)
    {
        aux=h[p];
        h[p]=h[p/2];
        h[p/2]=aux;
        addToHeap(p/2);
    }
}

void downHeap(int p)
{
    int fs,fd;
    heap aux;
    fs=(p<<1);
    fd=fs+1;
    if (fd<=h[0].x)
    {
        if (h[fd].x<h[fs].x && h[fd].x<h[p].x)
        {
            aux=h[p];
            h[p]=h[fd];
            h[fd]=aux;
            downHeap(fd);
            return;
        }
    }
    if (fs<=h[0].x)
        if (h[fs].x<h[p].x)
        {
            aux=h[p];
            h[p]=h[fs];
            h[fs]=aux;
            downHeap(fs);
            return;
        }
}

void solve()
{
    int a;
    for (int i=1;i<K;i++)
    {
        in>>a;
        h[++h[0].x].x=a;
        h[h[0].x].poz=i;
        addToHeap(h[0].x);
    }
    for (int i=K;i<=N;i++)
    {
        in>>a;
        h[++h[0].x].x=a;
        h[h[0].x].poz=i;
        addToHeap(h[0].x);
        while (h[1].poz<i-K+1)
        {
            h[1]=h[h[0].x--];
            downHeap(1);
        }
        suma+=h[1].x;
    }
    out<<suma<<"\n";
}
int main()
{
    scan();
    solve();
    return 0;
}