Cod sursa(job #825624)

Utilizator maritimCristian Lambru maritim Data 29 noiembrie 2012 11:57:21
Problema Deque Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include<stdio.h>
#include<fstream>
using namespace std;

ifstream f("deque.in");
FILE *g = fopen("deque.out","w");

struct Pair
{
    int first,second;
} ;

#define MaxN 5000100

struct Priority_queue
{
    Pair A[MaxN];
    int size;

    Priority_queue(void)
    {
        size = 0;
    }

    inline void swap(Pair &a,Pair &b)
    {
        Pair aux = a;
        a = b;
        b = aux;
    }

    inline void push(Pair val)
    {
        A[++size] = val;
        for(int p = size;p>>1 > 0 && A[p].first < A[p>>1].first;swap(A[p],A[p>>1]),p>>=1);
    }

    inline void pushDOWN(void)
    {
        int pozM;

        for(int p=1;(p<<1 <= size && A[p<<1].first < A[p].first) ||
            ((p<<1)+1 <= size && A[(p<<1)+1].first < A[p].first);)
        {
            pozM = p<<1;
            if(pozM + 1 <= size && A[pozM+1].first < A[pozM].first)
                ++ pozM;
            
            swap(A[p],A[pozM]);
            
            p = pozM;
        }
    }

    inline void pop(void)
    {
        A[1] = A[size--];
        pushDOWN();
    }

    inline Pair top(void)
    {
        return A[1];
    }
};

#define ll long long

int N,K;
ll Sol;
Priority_queue Q;

inline Pair make_Pair(int a,int b)
{
    Pair c = {a,b};

    return c;
}

void citire(void)
{
    f >> N >> K;
}

void Rezolvare(void)
{
    int a;

    for(int i=1;i<=K;i++)
    {
        f >> a;
        Q.push(make_Pair(a,i));
    }

    for(int i=K+1;i<=N+1;i++)
    {
        for(;Q.top().second < i-K;Q.pop());

        Sol += Q.top().first;

        f >> a;
        Q.push(make_Pair(a,i));
    }
}

int main()
{
    citire();
    Rezolvare();

    fprintf(g,"%lld\n",Sol);
}