跳到正文

题解

P12372 [蓝桥杯 2022 省 Python B] 最优清零方案 题解

wwqwq约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月26日
收录
2025年12月12日
更新
2026年9月10日
篇幅
约 3 分钟
获赞
1
题目
P12372

版本

  1. v1当前

和@Lyw_and_segment_tree duel这题,15min险胜。

注意到肯定要多用 2 操作,所以从左往右扫,只要能用 2 操作就用,一个区间使用 2 操作的次数为这个区间中的最小值,可以用线段树维护区间最小值和区间减。而剩下的数的和就是用 1 操作的次数。详见代码。

C++
#include <bits/stdc++.h>

using namespace std;

#define int long long
#define endl '\n'

int n, k, a[1000005], ans, sum;
struct node {int l, r, Min, lazy;} t[4000005];

void pushup(int xb) {t[xb].Min = min(t[xb * 2].Min, t[xb * 2 + 1].Min);}
void pushdown(int xb) {
	if (t[xb].lazy) {
		int s = t[xb].lazy;
		t[xb * 2].lazy += s; t[xb * 2 + 1].lazy += s;
		t[xb * 2].Min -= s; t[xb * 2 + 1].Min -= s; 
		t[xb].lazy = 0;
	}
}

void buld(int xb, int l, int r) {
	t[xb].l = l; t[xb].r = r; t[xb].lazy = 0;
	if (l == r) {t[xb].Min = a[l]; return ;}
	int mid = (l + r) / 2;
	buld(xb * 2, l, mid); buld(xb * 2 + 1, mid + 1, r);
	pushup(xb);
}
void change_(int xb, int l, int r, int s) {
	if (l <= t[xb].l && t[xb].r <= r) {
		t[xb].lazy += s;
		t[xb].Min -= s;
		return ;
	}
	pushdown(xb);
	int mid = (t[xb].l + t[xb].r) / 2;
	if (l <= mid) change_(xb * 2, l, r, s);
	if (r > mid) change_(xb * 2 + 1, l, r, s);
	pushup(xb);
}
int Ask(int xb, int l, int r) {
	if (l <= t[xb].l && t[xb].r <= r) return t[xb].Min;
	pushdown(xb);
	int mid = (t[xb].l + t[xb].r) / 2, res = 2147483647;
	if (l <= mid) res = min(res, Ask(xb * 2, l, r));
	if (r > mid) res = min(res, Ask(xb * 2 + 1, l, r));
	return res;
}

signed main() {
	std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	cin >> n >> k;
	for (int i = 1; i <= n; i++) cin >> a[i], sum += a[i];
	buld(1, 1, n);
	for (int i = 1; i <= n - k + 1; i++) {
		int res = Ask(1, i, i + k - 1);
		change_(1, i, i + k - 1, res);
		ans += res; sum -= res * k;
	}
	ans += sum;//操作 1
	cout << ans << endl;
	return 0;
}
原文
存档评论4 条抓取于