YbtOJ 「基础算法」第2章 贪心算法
例题1.奶牛晒衣服
注意:烘干 \(b\) 是指在每分钟烘干 \(a\) 的基础上额外增加 \(b\) !!1(太坑人了
二分答案,check 写法显然。
code
#include
using namespace std;
const int N=5e5+5;
int n,h[N],a,b;
int maxn;
bool check(int x)
{
if(b<0)
{
for(int i=1;i<=n;i++) if(a*x return 1; } int sum=0; for(int i=1;i<=n;i++) { if(a*x } if(sum<=x) return 1; else return 0; } int main() { scanf("%d%d%d",&n,&a,&b); for(int i=1;i<=n;i++) { scanf("%d",&h[i]); maxn=max(maxn,(h[i]+a-1)/a); } //b-=a; int l=1,r=maxn; while(l { int mid=(l+r)>>1; if(check(mid)) r=mid; else l=mid+1; } cout< return 0; } 例题2.雷达装置 首先将每个点对应可以放置雷达的区间映射到 x 轴上。按照区间右端点排序,贪心把雷达放在右端点。 code #include using namespace std; const int N=1005; typedef double db; int n,d; struct node{ db x,y; }a[N],b[N]; bool cmp(node x,node y){ return x.y } int main() { scanf("%d%d",&n,&d); for(int i=1;i<=n;i++) { scanf("%lf%lf",&a[i].x,&a[i].y); if(fabs(a[i].y)>d) {cout<<"-1"< db l=sqrt(1.0*(d*d-a[i].y*a[i].y)); b[i].x=a[i].x-l;b[i].y=a[i].x+l; } sort(b+1,b+n+1,cmp); db last=0;int ans=0; for(int i=1;i<=n;i++) { if(i==1) {last=b[i].y;ans++;} else { if(last
} } cout< return 0; } 例题3.畜栏预定 贪心,每个牛能放就放,不能就新开一个畜栏来放。 用优先队列维护当前畜栏中牛离开时间的最小值。时间复杂度 \(O(n\log n)\)。 code #include #define pii pair #define fi first #define se second using namespace std; const int N=5e4+5; int n,ans[N],cnt; struct node{ int l,r,id; }a[N]; bool cmp(node x,node y){ if(x.l==y.l) return x.r else return x.l } priority_queue int main() { scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d%d",&a[i].l,&a[i].r); a[i].id=i; } sort(a+1,a+n+1,cmp); cnt++;q.push(pii(a[1].r,1)); ans[a[1].id]=1; for(int i=2;i<=n;i++) { if(q.empty()) { ans[a[i].id]=1; q.push(pii(a[i].r,1)); continue; }