Pagini recente » Cod sursa (job #3243292) | Cod sursa (job #2161347) | Cod sursa (job #2131927) | Cod sursa (job #1358827) | Cod sursa (job #1053292)
#include<iostream>
#include <algorithm>
#include<fstream>
using namespace std;
ifstream f("deque.in");
ofstream g("deque.out");
int heap[5000001], ord[5000001], n, k, l, nr;
void urca(int nr, int poz)
{
while(poz>1 && heap[poz] < heap[poz/2])
{
swap(heap[poz], heap[poz/2]);
swap(ord[poz], ord[poz/2]);
poz=poz/2;
}
}
void coboara(int &nr, int poz)
{
int poz1;
while(poz*2+1 <= nr && (heap[poz]>heap[poz*2] || heap[poz]>heap[poz*2+1]))
{
poz1=poz*2;
if(heap[poz*2+1] < heap[poz1])
poz1=poz*2+1;
swap(heap[poz], heap[poz1]);
swap(ord[poz], ord[poz1]);
poz=poz1;
}
if(poz*2==nr && heap[poz] > heap[poz*2])
{
swap(heap[poz], heap[poz*2]);
swap(ord[poz], ord[poz*2]);
}
}
void insereaza(int &nr, int val)
{
l++;
nr++;
heap[nr]=val;
ord[nr]=l;
urca(nr, nr);
}
void delete_min(int &nr)
{
heap[1]=heap[nr];
ord[1]=ord[nr];
nr--;
coboara(nr, 1);
}
int main()
{
int i, x;
long long s=0;
l=0;
nr=0;
f>>n;
f>>k;
for(i=1;i<=k;i++)
{
f>>x;
insereaza(nr, x);
}
s+=heap[1];
for(i=k+1;i<=n;i++)
{
f>>x;
insereaza(nr, x);
if(l-ord[1]+1 > k)
while(l-ord[1]+1 > k)
delete_min(nr);
s+=heap[1];
}
g<<s;
}