Cod sursa(job #1047147)

Utilizator alexsuciuAlex Suciu alexsuciu Data 3 decembrie 2013 23:09:20
Problema Deque Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <iostream>
#include<fstream>
#include<algorithm>
#include<conio.h>

using namespace std;

long  heap[5000005],poz[5000005],a[5000005],nr,k;
long  i,x;
long long sum;

void urca(long &n,long pozi)
{
    while(pozi>1&& a[heap[pozi]]<a[heap[pozi/2]])
    {
        swap(heap[pozi],heap[pozi/2]);
        poz[heap[pozi]]=pozi;
        poz[heap[pozi/2]]=pozi/2;
        pozi/=2;

    }
}

void coboara(long &n,long pozi)
{
 {
    long poz1=0;

    while(pozi!=poz1) {
        poz1=pozi;

        if(2*poz1<=k && a[heap[pozi]]>a[heap[2*pozi]])
            pozi=2*poz1;
        if(2*poz1+1<=k && a[heap[pozi]]>a[heap[2*poz1+1]])
            pozi=2*poz1+1;

        swap(heap[pozi],heap[poz1]);
        poz[heap[pozi]]=pozi;
        poz[heap[poz1]]=poz1;

        }
}}

int main()
{long n=0,ct=1,lung;
    freopen("deque.in","r",stdin);
    freopen("deque.out","w",stdout);
    scanf("%ld%ld",&nr,&lung);
    for(i=1;i<=lung;i++)
    {   scanf("%ld",&x);
        a[++n]=x;
        heap[++k]=n;
        poz[n]=k;
        urca(n,k);
        }
    for(i=lung+1;i<=nr;i++)
            {sum+=a[heap[1]];
            a[ct]=-10000001;
            urca(n,poz[ct]);
            poz[heap[1]]=0;
            heap[1]=heap[k--];
            poz[heap[1]]=1;
            coboara(n,1);
            scanf("%ld",&x);
            a[++n]=x;
            heap[++k]=n;
            poz[n]=k;
            urca(n,k);
            ct++;
        }

        sum+=a[heap[1]];
        printf("%lld",sum);
    }