Cod sursa(job #2703089)

Utilizator ssenseEsanu Mihai ssense Data 7 februarie 2021 10:29:05
Problema Deque Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
typedef unsigned long long ull;
typedef long long  ll;
using namespace std;
#define FOR(n) for(int i=0;i<n;i++)
#define vt vector
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007
#define MOD2 998244353
#define MX 1000000000
#define nax 100005
#define MXL 1000000000000000000
#define PI 3.14159265
#define pb push_back
#define pf push_front
#define sc second
#define fr first
#define int ll
#define endl '\n'
#define ld long double

vector<int> read(int n) {vector<int> a; for (int i = 0; i < n; i++) { int x; cin >> x; a.pb(x);} return a;}


int32_t main(){
	startt;
	//freopen("deque.in", "r", stdin);
	//freopen("deque.out", "w", stdout);
	stack<pair<int, int>> s1, s2;
	int n, k;
	cin >> n >> k;
	int ans = 0;
	for(int i = 0; i < k; i++)
	{
		int el;
		cin >> el;
		if(s2.empty())
		{
			s2.push({el, el});
		}
		else
		{
			s2.push({el, min(el, s2.top().sc)});
		}
	}
	ans+=s2.top().sc;
	while(!s2.empty())
	{
		int el = s2.top().fr;
		if(s1.empty())
		{
			s1.push({el, el});
		}
		else
		{
			s1.push({el, min(el, s1.top().sc)});
		}
		s2.pop();
	}
	for(int i = k; i < n; i++)
	{
		int x;
		cin >> x;
		if(s1.empty())
		{
			while(!s2.empty())
			{
				int el = s2.top().fr;
				if(s1.empty())
				{
					s1.push({el, el});
				}
				else
				{
					s1.push({el, min(el, s1.top().sc)});
				}
				s2.pop();
			}
		}
		if(s2.empty())
		{
			s2.push({x, x});
		}
		else
		{
			s2.push({x, min(x, s2.top().sc)});
		}
		s1.pop();
		if(s1.empty())
		{
			ans+=s2.top().sc;
		}
		else
		{
			ans+=min(s1.top().sc, s2.top().sc);
		}
	}
	cout << ans << endl;
}