Pagini recente » Cod sursa (job #1225441) | Cod sursa (job #669459) | Cod sursa (job #2413008) | Cod sursa (job #2740097) | Cod sursa (job #1051461)
#include<fstream>
using namespace std;
int *heap, len = -1, *v;
void interschimba(int &a, int &b)
{
int aux = a;
a = b;
b = aux;
}
void sift(int nod)
{
int son;
do
{
son = 0;
if (nod * 2 <= len)
{
son = nod * 2;
if (nod * 2 + 1 <= len && v[heap[nod * 2 + 1]] < v[heap[nod * 2]])
son = nod * 2 + 1;
if (v[heap[son]] >= v[heap[nod]])
son = 0;
}
if (son)
{
interschimba(heap[nod], heap[son]);
nod = son;
}
} while (son);
}
void percolate(int nod)
{
int key = heap[nod];
while ((nod > 1) && (v[key] > v[heap[nod / 2]]))
{
heap[nod] = heap[nod / 2];
nod /= 2;
}
heap[nod] = key;
}
void insert(int nod)
{
heap[++len] = nod;
percolate(len);
}
void cut(int nod) {
heap[nod] = heap[len];
--len;
if ((nod > 1) && (v[heap[nod]] > v[heap[nod / 2]]))
percolate(nod);
else
sift(nod);
}
int main()
{
int n, k;
long long sum = 0;
ifstream f("deque.in");
f >> n >> k;
v = new int[n];
heap = new int[n];
for (int i = 0; i < n; i++)
{
f >> v[i];
while (len >= 0 && v[heap[0]] > v[i])
cut(0);
insert(i);
if (i >= k - 1)
{
sum += v[heap[0]];
if (heap[0] == i + 1 - k)
cut(0);
}
}
f.close();
ofstream g("deque.out");
g << sum;
g.close();
return 0;
}