Pagini recente » Clasament Urmasii lui Moisil 2017 Clasa 9-a | Cod sursa (job #199831) | Cod sursa (job #712927) | Cod sursa (job #2104469) | Cod sursa (job #1032940)
#include <stdio.h>
using namespace std;
FILE *f=fopen("deque.in","r");
FILE *g=fopen("deque.out","w");
int poz[5000005],h[5000005],v[5000005],i,n,nr,ct,x,k;
long long s;
void swapp(int a,int b)
{
int aux;
aux=h[a];
h[a]=h[b];
h[b]=aux;
poz[h[a]]=a;
poz[h[b]]=b;
}
void cern(int k)
{
int fiu=k;
while(fiu)
{
fiu=0;
if (2*k<=nr && v[h[2*k]]<v[h[k]])fiu=2*k;
if (2*k+1<=nr &&v[h[2*k+1]]<v[h[fiu]])fiu=2*k+1;
if (fiu!=0){swapp(k,fiu);k=fiu;}
}
}
void urc(int k)
{
while(k>=1 && v[h[k]]<v[h[k/2]])
{
swapp(k,k/2);
k=k/2;
}
}
void cut(int k)
{
swapp(k,nr);
nr--;
cern(k);
}
void insert()
{
h[++nr]=i;
poz[i]=nr;
urc(nr);
}
int main()
{
fscanf(f,"%d%d",&n,&k);
ct=1;
v[0]=-10000001;
for(i=1;i<=n;++i)
{
fscanf(f,"%d",&x);
v[i]=x;
if (i>k){cut(poz[ct]);ct++;}
insert();
if (i>=k)s+=v[h[1]]*1LL;
}
fprintf(g,"%lld",s);
fclose(g);
return 0;
}