Cod sursa(job #1049229)

Utilizator Dayanna000Amegica Dayanna Dayanna000 Data 7 decembrie 2013 08:34:50
Problema Deque Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <iostream>
#include <fstream>
using namespace std;
int a[5000001],n,huh[5000001];
void next(int a[],int n)
  {
      int i,ok=1,pozi=0,aux;
      i=1;
      while(ok==1)
        {
            if(2*i<=n && 2*i+1<=n)
               {
                   if(a[huh[2*i]]<a[huh[2*i+1]])
                     pozi=2*i;
                     else
                     pozi=2*i+1;
                   if(a[huh[i]]<a[huh[pozi]])
                     pozi=0;
               }
               else
            if(2*i<=n && a[huh[2*i]]<a[huh[i]])
              pozi=2*i;
               else
            if(2*i+1<=n && a[huh[2*i+1]]<a[huh[i]])
               pozi=2*i+1;
            if(pozi==0)
               ok=0;
               else
               {
                   aux=huh[i];
                   huh[i]=huh[pozi];
                   huh[pozi]=aux;
                   i=pozi;
                   pozi=0;
               }
        }
  }
int main()
{
    ifstream f("deque.in");
    ofstream g("deque.out");
    int i,poz,x,s,k,aux,m;
    f>>n>>k>>a[1];
    huh[1]=1;
    for(i=2;i<=k;++i)
       {
          f>>a[i];
          huh[i]=i;
          x=i;
          poz=i/2;
          while(poz>=1)
            {
                if(a[huh[x]]<a[huh[poz]])
                  {
                      aux=huh[poz];
                      huh[poz]=huh[x];
                      huh[x]=aux;
                  }
                x=poz;
                poz=poz/2;
            }
       }
    s=a[huh[1]];
    m=k;
    for(i=k+1;i<=n;++i)
      {
          f>>a[i];
          huh[i]=i;
          while(i-huh[1]+1>k)
            {
                huh[1]=huh[m];
                m--;
                next(a,m);
            }
          if(a[i]>a[huh[1]])
            {
                s=s+a[huh[1]];
                m++;
                huh[m]=i;
                next(a,m);
            }
            else
            {
                huh[1]=i;
                next(a,m);
                s=s+a[huh[1]];
            }
      }
    g<<s;
    f.close();
    g.close();
    return 0;
}