/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 2ms 4.527 MiB
#2 Accepted 20ms 2.82 MiB
#3 Accepted 26ms 2.812 MiB
#4 Accepted 25ms 2.574 MiB
#5 Accepted 27ms 4.75 MiB
#6 Accepted 44ms 7.633 MiB
#7 Accepted 47ms 15.66 MiB
#8 Accepted 47ms 14.609 MiB
#9 Accepted 48ms 14.77 MiB
#10 Accepted 48ms 15.145 MiB
#11 Accepted 47ms 14.539 MiB
#12 Accepted 48ms 14.68 MiB

Code

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define bug(a) cout << #a << " : " << a << endl;

const int N = 1e5 + 5;
int t1[N][18], t2[N][18], a[N];

void build1(int n){
	for(int i = 1; i <= n; i++){
		t1[i][0] = a[i];
	}
	for(int k = 1; k < 18; ++k){
		for(int i = 1; i + (1 << k)-1 <= n; ++i){
			t1[i][k] = min(t1[i][k-1], t1[i + (1 << (k-1))][k-1]);
		}
	}
}

int query1(int l, int r){
	int k = 31 - __builtin_clz(r - l + 1);
	return min(t1[l][k], t1[r - (1 << k) + 1][k]);
}

void build2(int n){
	for(int i = 1; i <= n; i++){
		t2[i][0] = a[i];
	}
	for(int k = 1; k < 18; ++k){
		for(int i = 1; i + (1 << k)-1 <= n; ++i){
			t2[i][k] = max(t2[i][k-1], t2[i + (1 << (k-1))][k-1]);
		}
	}
}

int query2(int l, int r){
	int k = 31 - __builtin_clz(r - l + 1);
	return max(t2[l][k], t2[r - (1 << k) + 1][k]);
}


void solve(){
	int n, k;	cin >> n >> k;

	for(int i = 1; i <= n; i++) cin >> a[i];

	deque<ll> dq;
	ll sum = 0, ans = 1e18;

	build1(n);
	build2(n);

	for(int i = 1; i <= n; i++){
		sum += a[i];
		dq.push_back(a[i]);
		//bug(sum)
		if ( dq.size() == k ) {
			ans = min(ans, sum);
			//bug(i)
			//cout << 1 << ' ' << i-k << '\n';
			//cout << i + 1 << ' ' << n << '\n';
			//cout << '\n';
			int mn1 = 1e9;
			if ( i - k >= 1 ) {
				mn1 = query1(1, i-k);
			}
			int mn2 = 1e9;
			if ( i + 1 <= n ) {
				mn2 = query1(i + 1, n);
			}
			//cout << mn1 << ' ' << mn2 << '\n';
			int mn = min(mn1, mn2);

			int mx = query2(i - k + 1, i);
			ll tmp = 1LL * sum - mx + mn;
			//bug(tmp)
			ans = min(ans, tmp);
			sum -= dq.front();
			dq.pop_front();
		}
	}

	if ( dq.size() == k ) {
			int mn1 = query1(1, n-k);
			int mn = mn1;

			int mx = query2(n - k + 1, n);
			ll tmp = sum - mx + mn;
			ans = min(ans, tmp);
			sum -= dq.front();
			dq.pop_front();
		}

	cout << ans << '\n';


	
}	

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);

	int tc = 1, cs = 0;
	cin >> tc;

	while(tc--){
		//cout << "Case # " << ++cs << ": " ;
		solve();
	}

}

Information

Submit By
Type
Submission
Problem
P1149 Swap and Minimize
Contest
LU IUJPC : Sylhet Division 2024
Language
C++17 (G++ 13.2.0)
Submit At
2024-12-09 05:25:00
Judged At
2024-12-09 05:25:00
Judged By
Score
100
Total Time
48ms
Peak Memory
15.66 MiB