Cod sursa(job #3150178)

Utilizator The_SupremacySus Impostor The_Supremacy Data 15 septembrie 2023 09:22:29
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#pragma GCC optimize("O3,unroll-loops")
#include <bits/stdc++.h>
using namespace std;
class InParser {
private:
	FILE *fin;
	char *buff;
	int sp;

	char read_ch() {
		++sp;
		if (sp == 4096) {
			sp = 0;
			fread(buff, 1, 4096, fin);
		}
		return buff[sp];
	}

public:
	InParser(const char* nume) {
		fin = fopen(nume, "r");
		buff = new char[4096]();
		sp = 4095;
	}

	InParser& operator >> (int &n) {
		char c;
		while (!isdigit(c = read_ch()) && c != '-');
		int sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}

	InParser& operator >> (long long &n) {
		char c;
		n = 0;
		while (!isdigit(c = read_ch()) && c != '-');
		long long sgn = 1;
		if (c == '-') {
			n = 0;
			sgn = -1;
		} else {
			n = c - '0';
		}
		while (isdigit(c = read_ch())) {
			n = 10 * n + c - '0';
		}
		n *= sgn;
		return *this;
	}
};
const int NMAX = 5*1e6;
deque<int>q;
int v[NMAX+5];
int main()
{
    InParser fin("deque.in");
    ofstream fout("deque.out");
    int n,k,a;fin>>n>>k;long long sum=0;
    for(int i=1;i<=n;i++){fin>>v[i];}
    for(int i=1;i<=k;i++){
        while(!q.empty()&&v[q.back()]>v[i]){
            q.pop_back();
        }
        q.push_back(i);
    }
    sum+=v[q.front()];int st=0;
    for(int i=k+1;i<=n;i++){
        st++;
        while(!q.empty()&&q.front()<=st){
            q.pop_front();
        }
        while(!q.empty()&&v[q.back()]>v[i]){
            q.pop_back();
        }
        q.push_back(i);
        sum+=v[q.front()];
    }
    fout<<sum<<'\n';
    return 0;
}