Cod sursa(job #1052946)

Utilizator alexsuciuAlex Suciu alexsuciu Data 11 decembrie 2013 22:20:52
Problema Deque Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include<cstdio>
#include<algorithm>

using namespace std;
FILE *f,*g;
int heap[5000005],poz[5000005],a[5000005],nr,k;
int i,x,ki,n;

void urca(int 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(int pozi)
{
 {
    int poz1=0;

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

        if(2*poz1<=n && a[heap[pozi]]>a[heap[2*poz1]])
            pozi=2*poz1;
        if(2*poz1+1<=n && 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()
{int ct=1;
long long sum=0;
f=fopen("deque.in","r");
g=fopen("deque.out","w");
    fscanf(f,"%d%d",&nr,&ki);
    for(i=1;i<=ki;i++)
    {
        fscanf(f,"%d",&x);
        a[++k]=x;
        heap[++n]=k;
        poz[k]=n;
        urca(n);
    }
    for(i=ki+1;i<=nr;i++)
    {
            sum+=a[heap[1]];
            a[ct]=12000000;
            heap[poz[ct]]=heap[n--];
            urca(poz[ct]);
            coboara(poz[ct]);
            fscanf(f,"%d",&x);
            a[++k]=x;
            heap[++n]=k;
            poz[k]=n;
            urca(n);
            ct++;
        }
        sum+=a[heap[1]];
        fprintf(g,"%lld",sum);
    }