[Ybtoj Chapter 2 Example 2] Radar device [Recursion]

Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here


Problem-solving ideas
as shown in the figure, for any building (x, y) (x, y)x,y ) , we calculate on the x-axis the radar construction interval [l,r] that can detect the building.
Insert picture description here
The Pythagorean theorem gives:l = x − radical sign (d 2 − y 2) l = x- radical sign (d^2-y^2)l=xRoot number ( D2and2 ),r = x + radical (d 2 − y 2) r=x + radical (d^2-y^2)r=x+Root number ( D2and2
d 2 − y 2 < 0 d^2-y^2<0 d2and2<0 d < y d<y d<At y , the building cannot be detected by radar, and can be directly output− 1 -11.

We can convert all buildings into radar construction intervals, and the problem is converted to: Given nnn intervals, as few points as possible above the number axis, so that each interval contains a point.

Greedy strategy:

  • Sort all intervals from smallest to largest right end point.
  • Consider each interval at once
  1. If the last selected point is included in the current interval, skip directly
  2. If the last selected point is not included in the current interval, a new point is placed at the right end of the interval.

PS: We can easily do this wrong. For example, my konjac is sorted directly, and then if the left end of the current point is greater than the left end of the current interval by 2 ∗ d 2*d2fromyears + + years ++a n s++ . This is wrong, because the range of the radar is a circle. This is to treat the range of the radar as ad ∗ dd*ddThe matrix of d .


Code

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
long long t,n,d,ans,x,y;
double w;
bool flag;
struct c{
    
    
	double x,y;
}a[3000];
bool cmp(const c&a,const c&b)
{
    
    
	return a.y<b.y;
}
int main() {
    
    
	scanf("%lld%lld",&n,&d);
	for(int i=1; i<=n; i++) {
    
    
		scanf("%lld%lld",&y,&x);
		if(abs(x)>d) 
			flag=1;
		a[i].x=y-sqrt(d*d-x*x);
		a[i].y=y+sqrt(d*d-x*x);
	}
	if(flag==1)
	{
    
    
		printf("-1");
		return 0;
	}
	sort(a+1,a+n+1,cmp);
	ans=1,w=a[1].y;
	for(int i=2; i<=n; i++) {
    
    
		if(a[i].x<=w&&a[i].y>=w)
			continue;
		else 
		{
    
    
			ans++;
			w=a[i].y;
		}
	}
	printf("%lld",ans);
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111707586