贪心基础
刚开始刷一本通,写篇博客记录一下吧!
题型1:求不相交的最大区间数
10000. 「一本通 1.1 例 1」活动安排 / #10007. 「一本通 1.1 练习 3」线段
按区间右端点下标排序,然后遍历即可
10002. 「一本通 1.1 例 3」喷水装置
区间右端点需要勾股计算,注意数据类型。同理排序后遍历
10003. 「一本通 1.1 例 4」加工生产调度
排序的条件为A在前比B在前的进度快则A排在前面
bool cmp(node x, node y) {
return x.a + max(y.a, x.b) + y.b < y.a + max(x.a, y.b) + x.b;
}
题型2:按给定期限选择顺序
10004. 「一本通 1.1 例 5」智力大冲浪
排序后按收益从大到小遍历,若无法在期限内完成则牺牲还未进行的任务来凑时间 O(
10008. 「一本通 1.1 练习 4」家庭作业
数据范围变为
使用并查集路径压缩优化。(即跳过已经统计过的任务)
for(int i = 1; i <= n; i++){
int x = Find(a[i].t);
if(x){
fa[x] = Find(x-1);
ans += a[i].w;
}
}
10009. 「一本通 1.1 练习 5」钓鱼
注意到走路方向和时间是固定的,因此可以预处理出一路不停走到i点的时间
(实际上预处理可以合并到运算过程当中)
ps: 本题dp做法复杂度较高且较不易实现,不推荐使用
(其实是dp版本调不出来了)
#include<bits/stdc++.h>
using namespace std;
int n, H, d[105], t[105], f[105], tot, ans;
priority_queue<int,vector<int>,greater<int> > q;
int main(){
scanf("%d%d", &n, &H);
H *= 12;
for(int i = 1; i <= n; i++) scanf("%d", &f[i]);
for(int i = 1; i <= n; i++) scanf("%d", &d[i]);
for(int i = 1; i < n; i++) scanf("%d", &t[i]);
for(int i = 1; i <= n && H>0; H-=t[i],i++){//要先改H后改i
int cnt = 0;
while(f[i]>0 && ++cnt < 10000){ q.push(f[i]); tot += f[i]; f[i] -= d[i]; }//限制循环次数,防止d[i]=0陷入死循环
while(q.size() > H){ tot -= q.top(); q.pop(); }//时间不够,只能把收益小的点都弹出
ans = max(ans, tot);
}
printf("%d", ans);
return 0;
}
题型3:贪心思想的数学问题
10005. 「一本通 1.1 练习 1」数列极差
不难发现结论:若
推广到
10010. 「一本通 1.1 练习 6」糖果传递
不同于NOIP2002均分纸牌,这道题是一个环,并且每一个糖果的移动都对答案产生贡献
显而易见,最终状态下每个人的糖果数都等于平均数ave
设
将第
同理将第
题目要求最小化
根据绝对值不等式,
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n, a[1000005], ave, t[1000005];
ll sum[1000005], ans;
int main(){
scanf("%d", &n);
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
sum[i] = a[i]+sum[i-1];
}
ave = sum[n] / n;
for(int i = 1; i <= n; i++){
t[i] = sum[n-1]-sum[i-1] - (n-i)*ave;
}
sort(t+1, t+n+1);
int x = t[(n+1)/2];
for(int i = 1; i <= n; i++) ans += abs(x-t[i]);
printf("%lld", ans);
return 0;
}