Pagini recente » Cod sursa (job #1237180) | Cod sursa (job #3005153) | Cod sursa (job #723588) | Cod sursa (job #41833) | Cod sursa (job #2808319)
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
deque <ll> q;
const int nmax=1e6;
ll arr[5*nmax+5],n,k,sum=0;
void printKMax(ll arr[], ll n, ll k)
{
// Create a Double Ended Queue,
// Qi that will store indexes
// of array elements
// The queue will store indexes
// of useful elements in every
// window and it will
// maintain decreasing order of
// values from front to rear in Qi, i.e.,
// arr[Qi.front[]] to arr[Qi.rear()]
// are sorted in decreasing order
std::deque<int> Qi(k);
/* Process first k (or first window)
elements of array */
int i;
for (i = 0; i < k; ++i)
{
// For every element, the previous
// smaller elements are useless so
// remove them from Qi
while ((!Qi.empty()) && arr[i] >=
arr[Qi.back()])
// Remove from rear
Qi.pop_back();
// Add new element at rear of queue
Qi.push_back(i);
}
// Process rest of the elements,
// i.e., from arr[k] to arr[n-1]
for (; i < n; ++i)
{
// The element at the front of
// the queue is the largest element of
// previous window, so print it
cout << arr[Qi.front()] << " ";
// Remove the elements which
// are out of this window
while ((!Qi.empty()) && Qi.front() <=
i - k)
// Remove from front of queue
Qi.pop_front();
// Remove all elements
// smaller than the currently
// being added element (remove
// useless elements)
while ((!Qi.empty()) && arr[i] >=
arr[Qi.back()])
Qi.pop_back();
// Add current element at the rear of Qi
Qi.push_back(i);
}
// Print the maximum element
// of last window
cout << arr[Qi.front()];
}
int main()
{
freopen("deque.in","r",stdin);
freopen("deque.out","w",stdout);
ios_base::sync_with_stdio(false);
cin.tie(0);
cin>>n>>k;
for(int i=0;i<n;++i)
cin>>arr[i];
int i;
for(i=0;i<k;++i){
while((!q.empty()) && arr[i]<=arr[q.back()])
q.pop_back();
q.push_back(i);
}
for(;i<n;++i){
sum+=arr[q.front()];
while((!q.empty()) && q.front()<=i-k)
q.pop_front();
while((!q.empty()) && arr[i]<=arr[q.back()])
q.pop_back();
q.push_back(i);
}
sum+=arr[q.front()];
cout<<sum;
}