Cod sursa(job #1052977)

Utilizator uagamagaMatei Rogoz uagamaga Data 11 decembrie 2013 23:52:34
Problema Deque Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
/*

Rezolvare cu heap-uri - 60 puncte

*/

#include <fstream>
using namespace std;

ifstream i("deque.in");
ofstream o("deque.out");

int H[1000001],n,ret[1000001],rn,pos[1000001],x,dl,k;
long long sum;


int father(int nod){return nod>>1;}
int right_son(int nod){return (nod<<1)+1;}
int left_son(int nod){return nod<<1;}
int min(){return ret[H[1]];}
void swap(int nod1,int nod2)
{
    int aux;
    aux = H[nod1];
    H[nod1] = H[nod2];
    H[nod2] = aux;
    pos[H[nod1]] = nod1;
    pos[H[nod2]] = nod2;
}
void up(int nod)
{

    if(nod==1 || ret[H[nod]]>=ret[H[father(nod)]]) return;
    swap(nod,father(nod));
    up(father(nod));
}
void dw(int nod)
{
    if(left_son(nod)>n || !H[nod]) return;
    if(ret[H[nod]]>ret[H[left_son(nod)]] && ret[H[nod]]>ret[H[right_son(nod)]] && ret[H[left_son(nod)]]<ret[H[right_son(nod)]])
    {
        swap(nod,left_son(nod));
        dw(left_son(nod));
    }
    else
    {
        if(ret[H[nod]]>ret[H[left_son(nod)]] && ret[H[nod]]>ret[H[right_son(nod)]])
        {
            swap(nod,right_son(nod));
            dw(right_son(nod));
        }
        else
        {
            if(ret[H[nod]]>ret[H[left_son(nod)]])
            {
                swap(nod,left_son(nod));
                dw(left_son(nod));
            }
            else
            {
                if(ret[H[nod]]>ret[H[right_son(nod)]])
                {
                    swap(nod,right_son(nod));
                    dw(right_son(nod));
                }

            }
        }
    }

}
void INS()
{
    ret[++rn] = x;
    H[++n] = rn;
    pos[rn] = n;
    up(n);
}
void DEL()
{

    H[pos[dl]] = H[n];
    n--;
    if(pos[dl]>1 && H[pos[dl]]<H[father(pos[dl])])
        up(pos[dl]);
    else
        dw(pos[dl]);
}


int main()
{
    int nr,j;

    i>>nr>>k;

    for(j=1;j<=nr;j++)
    {
        i>>x;
        INS();
        if(j>=k)
        {
            sum += min();
            ++dl;
            DEL();

        }



    }
    o<<sum;
    return 0;
}