Pagini recente » Cod sursa (job #1270981) | Cod sursa (job #1269814) | Cod sursa (job #1559947) | Cod sursa (job #490050) | Cod sursa (job #1058683)
#include <iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;
ifstream f("deque.in");
ofstream g("deque.out");
int i,n,k,v[5000001],heap[5000001],a[5000001],l;
long long suma;
void inserare(int x)
{
while (x/2>=1 && v[heap[x]] < v[heap[x/2]])
{
swap(heap[x],heap[x/2]);
a[heap[x]] = x;
a[heap[x/2]] = x/2;
x /= 2;
}
}
void pop(int x)
{
int y = 0;
while (x != y)
{
y = x;
if (y*2<=l && v[heap[x]]>v[heap[y*2]])
x = y*2;
if (y*2+1<=l && v[heap[x]]>v[heap[y*2+1]])
x = y*2+1;
swap(heap[x],heap[y]);
a[heap[x]] = x;
a[heap[y]] = y;
}
}
int main()
{
f>>n>>k;
for(i=1;i<=n;i++)
{
f>>v[i];
l++;
heap[l] = i;
a[heap[l]]=l;
inserare(l);
while (heap[1] <= i-k)
{
heap[1] = heap[l--];
a[heap[1]] = 1;
pop(1);
}
if (i >= k)
suma += v[heap[1]];
}
g<<suma;
return 0;
}