Cod sursa(job #3375451)

Utilizator ionutpop118Pop Ioan Cristian ionutpop118 Data 12 noiembrie 2026 02:47:31
Problema Deque Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.75 kb
#include <stdio.h>
#include <ctype.h>
#include <fstream>

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;
	}
};

const int N_MAX = 5e6;

InParser fin("deque.in");
ofstream fout("deque.out");

struct Stack_t {
    int arr[N_MAX + 1];
    int top_stack_pointer;
    int bot_stack_pointer;

    void push_top(int x) {
        arr[top_stack_pointer++] = x;
    }

    int top() {
        return arr[top_stack_pointer - 1];
    }

    int bot() {
        return arr[bot_stack_pointer];
    }

    void pop_top() {
        top_stack_pointer--;
    }

    void pop_front() {
        bot_stack_pointer++;
    }

    bool empty() {
        return bot_stack_pointer == top_stack_pointer;
    }
};

int v[N_MAX + 1];
Stack_t st;

int main() {
    int i, n, k;
    long long ans = 0;

    fin >> n >> k;
    for (i = 1; i <= n; i++) {
        fin >> v[i];
        
        while (!st.empty() && v[i] <= v[st.top()]) {
            st.pop_top();
        }

        st.push_top(i);
        if (i >= k) {
            ans = ans + v[st.bot()];
        }

        if (st.bot() == i - k + 1) {
            st.pop_front();
        }
    }

    fout << ans;
    return 0;
}