Pagini recente » Cod sursa (job #2728034) | Cod sursa (job #1312857) | Cod sursa (job #2153218) | Cod sursa (job #2815128) | Cod sursa (job #3127318)
#include <iostream>
#include <fstream>
#include <vector>
#define MAX_SIZE 5000010
using namespace std;
ifstream f("deque.in");
ofstream g("deque.out");
template <typename T>
class Deque {
private:
T* data;
size_t front_index;
size_t back_index;
size_t capacity;
public:
Deque() : front_index(MAX_SIZE / 2), back_index(MAX_SIZE / 2 + 1), capacity(MAX_SIZE) {
data = new T[MAX_SIZE];
}
~Deque() {
delete[] data;
}
void push_front(T x) {
if (front_index == 0) {
throw std::runtime_error("Deque is full");
}
data[--front_index] = x;
}
void push_back(T x) {
if (back_index == capacity - 1) {
throw std::runtime_error("Deque is full");
}
data[back_index++] = x;
}
void pop_front() {
if (empty()) {
throw std::runtime_error("Deque is empty");
}
++front_index;
}
void pop_back() {
if (empty()) {
throw std::runtime_error("Deque is empty");
}
--back_index;
}
T& front() {
if (empty()) {
throw std::runtime_error("Deque is empty");
}
return data[front_index];
}
T& back() {
if (empty()) {
throw std::runtime_error("Deque is empty");
}
return data[back_index - 1];
}
bool empty() const {
return size() == 0;
}
size_t size() const {
return back_index - front_index;
}
};
int main()
{
Deque<pair<long long, long long>> deque;
vector<long> numbers;
long long no_of_elements, interval, x, sum = 0, last;
f >> no_of_elements >> interval;
for(long long i=0; i<no_of_elements; i++){
f >> x;
numbers.push_back(x);
}
for(long long i=0; i<no_of_elements; i++){
while(!deque.empty() && numbers[i] <= deque.back().first){
deque.pop_back();
}
deque.push_back({numbers[i], i});
if(deque.front().second <= i - interval) deque.pop_front();
if(i >= interval - 1){
sum += deque.front().first;
}
}
g << sum;
return 0;
}