雷达安装
Solution
这一道题又是一个典型的区间问题,可以抽象理解为选出尽量少的点,使每个区间至少有一个点。
可以通过贪心的方法来做,有两种方法,很明显这个点要放在区间的末尾,能够更好地共享。
1.1. 通过排序左端点
将左端点从小到大排,能安排的尽量在原有的基础上往前挪,因为不会影响之前得到的值。
具体实现
sort(a+1,a+n+1,cmp); int num=1; double pos=a[1].y; for(int i=2;i<=n;i++) if(pos<a[i].x)//不能包含 ++num,pos=a[i].y;//就新建一个来包含它 else pos=min(pos,a[i].y);//尽量往后挪
2.通过排序右端点
这种方法更为简单,只要考虑能不能往放得下就OK了。如果能包含,就继续,如果不能就新建一个。
具体实现
sort(a+1,a+n+1,cmp); int num=1; double pos=a[1].y; for(int i=2;i<=n;i++) if(pos<a[i].x) ++num,pos=a[i].y;
综上,完整代码(方法1)
#include<bits/stdc++.h> using namespace std; int n,kase; double d,x,y; struct node{double x,y;}a[1005]; bool cmp(node a,node b){return a.x<b.x;} void solve(){ if(!n)return; for(int i=1;i<=n;i++){ scanf("%lf %lf",&x,&y); if(y>d)return printf("Case %d: -1\n",++kase),void(); a[i].x=x-sqrt(d*d-y*y);a[i].y=x+sqrt(d*d-y*y); } sort(a+1,a+n+1,cmp); int num=1; double pos=a[1].y; for(int i=2;i<=n;i++) if(pos<a[i].x) ++num,pos=a[i].y; else pos=min(pos,a[i].y); printf("Case %d: %d\n",++kase,num); } int main(){ while(scanf("%d %lf",&n,&d)&&n) solve(); }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步