跳到正文

学习·文化课

贪心构造 - 2025/12/20 学习记录

Limit_Yank_Peak约 21 分钟
原文
文章信息与版本

文章信息

发布
2025年12月20日
收录
2026年8月15日
更新
2026年11月8日
篇幅
约 21 分钟

版本

  1. v1当前

前言

666题单发下来发现很多都写过。

课件里 P1792 及以前都是做完的,没有写在总结里的都是之前做过的。

课件链接地址

『来自123云盘用户liyp的分享』greedy and constructive algorithms.pdf

链接:https://www.123865.com/s/HPk0jv-PnA7A

开始做题

P9207 灭罪「正直者之死」

一开始把它想成了反悔贪心,但是写到后面想到,用大根堆固然可以保证在任意时刻不会发生越界,但是由于数组的不单调性,很有可能不是最优解。例如减去一个数之后反而超出了限制。

这道题目显然是一道分治贪心。

考虑对正负的数分别放进一个数组。对正数组从小到大排序,对负数组从大到小排序。双指针,每次操作选择尽可能更优(结果更靠近 00 )的方案。暴力双指针万岁!

C++
#include<bits/stdc++.h>
#define int long long
namespace florr {
	inline int read() {
		int x = 0, f = 1;
		char ch = getchar();
		while (ch < '0' || ch > '9') {
			if (ch == '-')
				f = -1;
			ch = getchar();
		}
		while (ch >= '0' && ch <= '9')
			x = x * 10 + ch - '0', ch = getchar();
		return x * f;
	}
	void write(int x) {
		if (x < 0)
			putchar('-'), x = -x;
		if (x > 9)
			write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace florr;
using namespace std;
const int MAXN = 510;
int n, k, a[MAXN], ans = 0ll;
int maxl, minl;
vector<int>l, b;
bool cmp(int x, int y) {
	return x > y;
}
signed main() {
	n = read();
	k = read();
	for (int i = 1; i <= n; i++) {
		a[i] = read();
		if (a[i] == 0ll) ans ++;
		if (a[i] < 0ll) l.emplace_back(a[i]);
		if (a[i] > 0ll) b.emplace_back(a[i]);
	}
	maxl = (1 << (k - 1)) - 1;
	minl = -(1 << (k - 1));
	sort(l.begin(), l.end(), cmp);
	sort(b.begin(), b.end());
	int pos1 = 0, pos2 = 0, sum = 0ll;
	l.emplace_back(9178);
	b.emplace_back(9178);
	int lsize = l.size() - 1;
	int bsize = b.size() - 1;
	// pos1 big 数组的指针,pos2 low 数组的指针
	while (pos1 < (int)bsize or pos2 < (int)lsize) {

		if (sum + b[pos1] <= maxl and pos1 < (int)bsize) {
			if (sum + l[pos2] >= minl and pos2 < (int)lsize) {
				if (abs(sum + b[pos1]) < abs(sum + l[pos2])) {
					ans++;
					sum += b[pos1];
					pos1++;
				} else {
					ans++;
					sum += l[pos2];
					pos2++;
				}
			} else {
				ans++;
				sum += b[pos1];
				pos1++;
			}
		} else if (sum + l[pos2] >= minl and pos2 < (int)lsize) {
			ans++;
			sum += l[pos2];
			pos2++;
		} else {
			break;
		}

	}
	write(ans);
	return 0;
}

CF1707A Doremy’s IQ

这是一个非常好的反向贪心。

这道题目正向应该是一个二分。但是我不想写。

反向思考了一下,发现显然的如果一场比赛会发生扣分,那么要么不选,要么就让接下来所有的比赛全部报名,这显然是一个最优解。

反向思考一下,假如你一开始的智商 iqiq 为 00,每打一场 ai≥iqa_i \ge iq 的比赛你的 iqiq 就会加 11,问你在保证 iq≤qiq \le q 的情况下最多能打多少场比赛。

用这种思路同样能够证明我在第二段提出的策略。

开始写题,注意要判边界。

Accepted - CF1707A Doremy’s IQ

C++
#include<bits/stdc++.h>
#define int long long
namespace florr {
	inline int read() {
		int x = 0, f = 1;
		char ch = getchar();
		while (ch < '0' || ch > '9') {
			if (ch == '-')
				f = -1;
			ch = getchar();
		}
		while (ch >= '0' && ch <= '9')
			x = x * 10 + ch - '0', ch = getchar();
		return x * f;
	}
	void write(int x) {
		if (x < 0)
			putchar('-'), x = -x;
		if (x > 9)
			write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace florr;
using namespace std;
const int MAXN = 1e5 + 10;
int n, q, a[MAXN];
void solve() {
	n = read();
	q = read();
	for (int i = 1; i <= n; i++) {
		a[i] = read();
	}
	int t = 0, pos = n + 1;
	for (int i = n; t <= q - 1 and i > 0; i--) {
		if (t < a[i]) t++;
		pos = i;
	}
	int ans = n + 1 - pos;
	for (int i = 1; i < pos; i++) {
		if (a[i] <= q) {
			ans++;
			write(1);
		} else write(0);
	}
	for (int i = pos; i <= n; i++) {
		write(1);
	}
	putchar('\n');
	return;
}
signed main() {
	int T = read();
	while (T--) {
		solve();
	}
	return 0;
}

CF1779C Least Prefix Sum

这是一道非常经典的数学题。(Doge

首先你猜猜他为什么要给你这个正式化的结论:

正式结论

更正式的,对于每个 k=1,2,…,nk = 1,2,…,n,都应满足:

a1+a2+…+ak≥a1+a2+…+ama_1+a_2+…+a_k \ge a_1 + a_2 + … + a_m

为什么两个省略号不一样?

然后你推一下这道题的目标:

k≥m:∑i=m+1kai≤0k \ge m:\sum_{i=m+1}^{k} a_i \le 0

另有:

k≤m:∑i=k+1mai≤0k \le m:\sum_{i=k+1}^{m} a_i \le 0

注意 k∈[1,n]k \in [1,n]。

这个时候题目只能说显然了。所以任意以 mm 为端点的区间和应为非正数。

更加正式的:

对于任意正整数k∈[2,n]且k≠m,应满足∑i=min⁡(k,m)max(k,m)ai≤0对于任意正整数 k \in [2,n] 且 k \ne m,应满足 \sum_{i=\min(k,m)}^{max(k,m)} a_i \le 0

呸呸呸我推的什么式子。

好像前面的式子都是错的。

重新写一下:

对于任意k∈[2,m],应满足∑i=kmai≤0对于任意 k \in [2,m],应满足\sum_{i=k}^{m} a_i \le 0

同时:

对于任意k∈[m+1,n],应满足∑i=knai≥0对于任意 k \in [m+1,n],应满足 \sum_{i=k}^{n} a_i \ge 0

直接通过从 mm 开始枚举 kk 来进行暴力修改即可。顺便再加一个堆维护。

(666把这个唐的要死的式子当成数竞推了半天)

(感谢推了半个小时式子的我)

C++
#include<bits/stdc++.h>
#define int long long
namespace florr {
	inline int read() {
		int x = 0, f = 1;
		char ch = getchar();
		while (ch < '0' || ch > '9') {
			if (ch == '-')
				f = -1;
			ch = getchar();
		}
		while (ch >= '0' && ch <= '9')
			x = x * 10 + ch - '0', ch = getchar();
		return x * f;
	}
	void write(int x) {
		if (x < 0)
			putchar('-'), x = -x;
		if (x > 9)
			write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace florr;
using namespace std;
const int MAXN = 2e5 + 10;
int n, m, a[MAXN];
void solve() {
	n = read();
	m = read();
	for (int i = 1; i <= n; i++) {
		a[i] = read();
	}
	priority_queue<pair<int, int> >q;
	int sum = 0ll;
	int ans = 0ll;
	for (int i = m; i > 1; i--) {
		sum += a[i];
		q.push({a[i], i});
		if (sum > 0) {
			pair<int, int> x = q.top();
			q.pop();
			ans++;
			sum -= 2 * x.first;
		}
	}
	priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > >q2;;
	sum = 0ll;
	for (int i = m + 1; i <= n; i++) {
		sum += a[i];
		q2.push({a[i], i});
		if (sum < 0) {
			pair<int, int> x = q2.top();
			q2.pop();
			ans++;
			sum -= 2 * x.first;
		}
	}
	write(ans);
	putchar('\n');
	return;
}
signed main() {
	int T = read();
	while (T--) {
		solve();
	}
	return 0;
}

P9210 蓬莱「凯风快晴 −富士火山−」

观察样例发现最优解有根。无需证明。

然后就卡住了。

看了题解,全是从上往下筛的,但是我不会。

去翻前面的总结,发现这道题目好像可以反向贪心。

题目不是要求每一层的节点数单调递增吗,所以直接从最大的(默认最后一层)开始,然后不断往上推。当发现无法递增时,考虑两种情况。

  • 因为第 i+1i+1 层的节点有 sonsi+1sons_{i+1} 个,所以第 ii 层一定会有至少 sonsi+1sons_{i+1} 个父亲节点 + 叶子节点。此时我们可以把它删到只剩 sonsi+1sons_{i+1} 个节点。
  • 交上去发现是错的,考虑假如第 ii 层有 1e91e9 个节点,但是之后往下所有的层数只有 1e81e8 个,这个时候压进去显然是不优的,所以考虑这种极端情况。

交上去就 A 了。但是发现了一个漏洞。假如因为第一种情况,导致第 ii 层被压缩,是否会导致上面的部分选择也被压缩呢。题目是通过了,但是这一点我要打个问号。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
namespace florr {
	inline int read() {
		int x = 0, f = 1;
		char ch = getchar();
		while (ch < '0' || ch > '9') {
			if (ch == '-')
				f = -1;
			ch = getchar();
		}
		while (ch >= '0' && ch <= '9')
			x = x * 10 + ch - '0', ch = getchar();
		return x * f;
	}
	void write(int x) {
		if (x < 0)
			putchar('-'), x = -x;
		if (x > 9)
			write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace florr;
const int MAXN = 5e5 + 10;
int n, m, deep[MAXN], fa[MAXN], sons[MAXN], max_deep = 0;
vector<int>G[MAXN];
void dfs_init(int x, int father) {
	deep[x] = deep[father] + 1;
	max_deep = max(max_deep, deep[x]);
	sons[deep[x]]++;
	fa[x] = father;
	for (auto i : G[x]) {
		if (i != father) {
			dfs_init(i, x);
		}
	}
	return;
}
signed main() {
	n = read();
	for (int i = 1; i < n; i++) {
		int u = read(), v = read();
		G[u].emplace_back(v);
		G[v].emplace_back(u);
	}
	dfs_init(1, 0);
	int ans = sons[max_deep];
	for (int i = max_deep - 1; i > 0; i--) {
		if (sons[i] > sons[i + 1]) {
			if (sons[i] > sons[i + 1] + ans) {
				ans = sons[i];
			} else {
				sons[i] = sons[i + 1];
				ans += sons[i];
			}
		} else {
			ans += sons[i];
		}
	}
	write(ans);
	return 0;
}

P3619 魔法

显然的简单贪心,为了尽可能完成更多任务,肯定是让自己的上限尽可能更高。优先做加上限的即可。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 1e5 + 10;
const string R="+1s",F="-1s";
int n,t;
struct code{
	int s, t; 
};
code s1[MAXN],s2[MAXN]; 
bool cmp2(code x, code y){
	return x.s < y.s;
}
bool cmp1(code x, code y){
	return (x.s + x.t) > (y.s + y.t);
}
void solve(){
	int l1=0, l2=0;
	cin>>n>>t;
	
	for(int i=1;i<=n;i++){
		code x;
		cin>>x.s>>x.t;
		if(x.t >= 0) {
			s2[++l2] = x; 
		} else {
			s1[++l1] = x; 
		}
	}
	
	sort(s1+1, s1+l1+1, cmp1); 
	sort(s2+1, s2+l2+1, cmp2);
	for(int i=1;i<=l2;i++){
		if(s2[i].s >= t){ 
			cout<<F<<endl;
			return;
		}
		t += s2[i].t;
	}
	for(int i=1;i<=l1;i++){
		if(s1[i].s >= t){ 
			cout<<F<<endl;
			return;
		}
		t += s1[i].t;
		if(t <= 0){ 
			cout<<F<<endl;
			return;
		}
	}
	
	cout<<R<<endl;
}

signed main(){
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	int T;
	cin>>T;
	while(T--){
		solve();
	}
	return 0;
}

P1792 [国家集训队] 种树

第一眼看上去像是DP,然后打了一个线性DP出来,然后就被无情的艹死了。

交给豆包,发现少看了一个条件,只能种 mm 棵树,但是显然如果硬开状态肯定是会起飞的。

所以我们考虑贪心。发现如果只按最大值贪心,那么显然是会假掉的,例如一个形如 2 3 2 的数据,显然是会被卡掉的。

对这种情况进行分析,发现我们在选择了 3 以后,不一定要直接删除,可以把它换为替换成周围的的贡献,形如 pi=pi−1+pi+1−pip_i = p_{i-1} + p_{i+1} - p_i,这样就可以考虑用周围的替换中间的情况了。

但是周围的不一定是相邻的,所以现学双向链表动态维护一个元素的邻接元素。

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
namespace florr{
	inline int read()
	{
		int x = 0, f = 1;
		char ch = getchar();
		while (ch<'0' || ch > '9')
		{
			if (ch == '-')
				f = -1;
			ch = getchar();
		}
		while (ch >= '0' && ch <= '9')
			x = x * 10 + ch - '0', ch = getchar();
		return x * f;
	}
	void write(int x)
	{
		if (x < 0)
			putchar('-'), x = -x;
		if (x > 9)
			write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace florr;
const int MAXN = 2e5 + 10;
int a[MAXN],n,m;
struct Node{
	int val,l,r;
};
Node p[MAXN];
bool flag[MAXN];
void premove(int x){
	p[p[p[x].l].l].r=x;
	p[p[p[x].r].r].l=x;
	p[x].l=p[p[x].l].l;
	p[x].r=p[p[x].r].r;
}
signed main()
{
	priority_queue<pair<int,int> >q;
	n=read();m=read();
	for(int i=1;i<=n;i++){
		a[i]=read();
		p[i].val=a[i];
		p[i].l=i-1;
		p[i].r=i+1;
		q.push({a[i],i});
	}
	if(m*2>n) {
		cout<<"Error!";
		return 0;
	}
	p[1].l=n,p[n].r=1;
	int ans = 0ll;
	for(int i=1;i<=m;i++){
		while(!q.empty()){
			if(flag[q.top().second]) q.pop();
			else break;
		}
		pair<int,int> now = q.top();q.pop();
		ans += now.first;
		flag[p[now.second].l]=flag[p[now.second].r]=1;
		p[now.second].val = p[p[now.second].l].val + p[p[now.second].r].val - p[now.second].val;
		q.push(make_pair(p[now.second].val,now.second));
		premove(now.second);
	}
	write(ans);
	return 0;
}

大总结

我总结的常考的贪心类型

  • 反悔贪心(题单里没有,但是CSPS+NOIP)。总的来说就是要考虑反悔的优先级问题。另外反悔贪心仅限有序的选择,对于无序的选择(例如 T1)就不能用。
  • 数学 + 贪心(例如T3)。确实对于一些不等式和等式,通过数学转换可以理解为一个非常简单的区间问题或树上问题。
  • 分治贪心,最常见的就是正负数分治。
  • 反向贪心,通过对问题反向理解寻求更优的贪心思路。(但是好像所有的反向贪心都有一个正向的题解。)

贪心的题目我觉得很难得一点就是贪心策略的证明。很多时候对于一种策略的证明真的只能源于经验和感觉。例如今天的T1,如果不是做了这道题,我都不太清楚反悔贪心的局限性。理性的证明非常难。

第二点,很多贪心的题目加上一些细小的细节之后就很容易思考了。例如今天的T4,如果没有发现最优解一定包含根,这道题目几乎无解。

总结:菜就多练。

原文