Pagini recente » Cod sursa (job #2228987) | Cod sursa (job #1632334) | Cod sursa (job #1488035) | Cod sursa (job #3124268) | Cod sursa (job #1052946)
#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);
}