Pagini recente » Cod sursa (job #1887090) | Cod sursa (job #1334282) | Cod sursa (job #1214703) | Cod sursa (job #1045902) | Cod sursa (job #3170820)
#include <fstream>
#include <deque>
const int maxn = 5000010;
using namespace std;
int n, k;
int a[maxn];
deque<int> dq;
int64_t Sum = 0;
int main() {
ifstream fin("deque.in");
ofstream fout("deque.out");
fin >> n >> k;
for (int i = 1; i <= n; i++)
fin >> a[i];
for (int i = 1; i <= n; i++) {
// Cât timp elementul curent este mai mic decât ultimul element din deque,
// eliminăm pozitia ultimului element din deque
while (not dq.empty() and a[i] <= a[dq.back()])
dq.pop_back();
dq.push_back(i); // Adaugăm poziția elementului curent în deque
if (i - dq.front() == k)
dq.pop_front();
if (i >= k)
Sum += a[dq.front()];
}
fout << Sum << '\n';
return 0;
}
/*
Adaugam -7
-7
Adaugam 9
-7 9
A sosit 2. Eliminam ultimul
-7
Adaugam 2
-7 2
0 + -7 = -7
Adaugam 4
-7 2 4
Eliminam primul
2 4
-7 + 2 = -5
A sosit -1. Eliminam ultimul
2
A sosit -1. Eliminam ultimul
Adaugam -1
-1
-5 + -1 = -6
Adaugam 5
-1 5
-6 + -1 = -7
Adaugam 6
-1 5 6
-7 + -1 = -8
Adaugam 7
-1 5 6 7
Eliminam primul
5 6 7
-8 + 5 = -3
A sosit 1. Eliminam ultimul
5 6
A sosit 1. Eliminam ultimul
5
A sosit 1. Eliminam ultimul
Adaugam 1
1
-3 + 1 = -2
. i
1 2 3 4 5 6 7
- - -
- - -
- - -
- - -
- - -
*/