Pagini recente » Cod sursa (job #1354775) | Cod sursa (job #1167098) | Cod sursa (job #2289463) | Cod sursa (job #355654) | Cod sursa (job #1860017)
#include<bits/stdc++.h>
#define NMAX 5000000
using namespace std;
int N, K, L;
int a[NMAX], h[NMAX], p[NMAX];
long long Sum;
inline int father(int child)
{return child/2;}
inline int left_son(int father)
{return father*2;}
inline int right_son(int father)
{return father*2+1;}
int swap_h(int x, int y)
{
int aux;
aux = h[x]; h[x] = h[y]; h[y] = aux;
}
void percolate(int nod)
{
while(father(nod) >= 1 && a[h[nod]] < a[h[father(nod)]])
{
swap_h(nod, father(nod));
p[h[nod]] = nod;
p[h[father(nod)]] = father(nod);
nod = father(nod);
}
}
void sift(int nod)
{
int son = 0;
while(son != nod)
{
son = nod;
if(left_son(son) <= L && a[h[left_son(son)]] < a[h[nod]] ) nod = left_son(son);
if(right_son(son) <= L && a[h[right_son(son)]] < a[h[nod]] ) nod = right_son(son);
swap_h(nod, son);
p[h[son]] = son;
p[h[nod]] = nod;
}
}
int main()
{
freopen("deque.in", "r", stdin);
freopen("deque.out", "w", stdout);
scanf("%d %d ", &N, &K);
int i;
for (i = 1; i <= N; i++)
{
scanf("%d ", &a[i]);
L++;
h[L] = i;
p[h[L]] = L;
percolate(L);
while (h[1] <= i-K)
{
h[1] = h[L--];
p[h[1]] = 1;
sift(1);
}
if (i >= K) Sum += a[h[1]];
}
printf("%lld", Sum);
return 0;
}