Pagini recente » Cod sursa (job #1549302) | Cod sursa (job #2105445) | Cod sursa (job #180952) | Cod sursa (job #1402041) | Cod sursa (job #2887321)
#include <iostream>
#include <fstream>
using namespace std;
template <class Type>
class Deque
{
private:
Type* storage;
int max_size,front,back;
void shift_left(int pos)
{
for (int i = back; i <= front; ++i)
storage[i - pos] = storage[i];
back -= pos;
front -= pos;
};
void shift_right(int pos)
{
for (int i = front; i >= back; --i)
storage[i + pos] = storage[i];
back += pos;
front += pos;
};
public:
Deque(int size)
{
max_size = size;
storage = new Type[max_size];
back = max_size / 2 - 1;
front = max_size / 2 - 2;
}
~Deque()
{
delete[] storage;
}
void push_front(Type nr)
{
if (front == max_size - 1)
shift_left(back);
storage[++front] = nr;
}
void push_back(Type nr)
{
if (back == 0)
shift_right(front);
storage[--back] = nr;
}
Type peek_front()
{
if (front <= max_size - 1)
return storage[front];
return Type();
}
Type peek_back()
{
if (back >= 0)
return storage[back];
return Type();
}
void pop_front()
{
if (!empty())
--front;
}
void pop_back()
{
if (!empty())
++back;
}
bool empty()
{
if (front < back)
return 1;
return 0;
}
void debug_afis()
{
for (int i = back; i <= front; ++i)
cout << storage[i] << endl;
cout << endl;
}
};
struct pereche
{
int first, second;
pereche() : first(0), second(0) {};
pereche(int f, int s) : first(f), second(s){};
friend ostream& operator<<(ostream& out, pereche p)
{
out << p.first << " " << p.second;
return out;
}
};
int main()
{
ifstream in("deque.in");
ofstream out("deque.out");
int n, k, nr;
long long sum = 0;
in >> n >> k;
Deque<pereche> mins(2*k - 2);
for(int i=0; i<n; ++i)
{
in >> nr;
while (!mins.empty() && nr < mins.peek_front().second)
mins.pop_front();
pereche ind_nr(i, nr);
mins.push_front(ind_nr);
if (mins.peek_back().first <= i - k)
mins.pop_back();
/*mins.debug_afis();*/
if(i>=k - 1)
sum += mins.peek_back().second;
}
in.close();
out << sum;
out.close();
}