hdu 4643(简单计算几何)

GSM

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)


Problem Description
Xiao Ming is traveling around several cities by train. And the time on the train is very boring, so Xiao Ming will use the mobile Internet. We all know that mobile phone receives the signal from base station and it will change the base station when moving on the train. Xiao Ming would like to know how many times the base station will change from city A to city B.
Now, the problem is simplified. We assume the route of train is straight, and the mobile phone will receive the signal from the nearest base station.
 

Input
Multiple cases. For each case, The first line: N(3<=N<=50) - the number of cities, M(2<=M<=50) - the number of base stations. Then there are N cities with coordinates of (x, y) and M base stations with coordinates of (x, y) - (0<=x<=1000, 0<=y<=1000, both x and y is integer).Then there is a number : K, the next, there are K queries, for each query, each line, there are two numbers: a, b.
 

Output
For each query, tell Xiao Ming how many times the base station will change from city a to city b.
 

Sample Input
   
   
   
   
4 4 0 2 1 3 1 0 2 0 1 2 1 1 2 2 2 1 4 1 2 1 3 1 4 3 4
 

Sample Output
   
   
   
   
0 1 2 1
Hint
The train way from a to b will not cross the point with the same distance from more than 2 base stations. (For the distance d1 and d2, if fabs(d1-d2)<1e-7, we think d1 == d2). And every city exactly receive signal from just one base station.
 

解题思路:要分析从A->B所切换的基站数,一般的想法就是模拟从A->B的路线,每走一小段判断一下是否有切换。这里可以用分治算法,每次都是一半一半的分析。详见代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

const int maxn = 55;
const double eps = 1e-7;
struct Point
{
	double x,y;
	Point() { }
	Point(double _x,double _y)
	{
		x = _x;
		y = _y;
	}
}city[maxn],base[maxn];
int n,m;

double dis(Point a,Point b)
{
	return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}

int belong(Point p)
{
	int k;
	double Min = 100000000;
	for(int i = 1; i <= m; i++)
		if(dis(p,base[i]) < Min)
		{
			Min = dis(p,base[i]);
			k = i;
		}
	return k;
}

int find(Point l,Point r)
{
	int k1 = belong(l), k2 = belong(r);
	if(k1 == k2) return 0;
	if(dis(l,r) <= eps) return 1;
	Point m = Point((l.x + r.x) / 2, (l.y + r.y) / 2);
	return find(l,m) + find(m,r);
}

int main()
{
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(int i = 1; i <= n; i++)
			scanf("%lf%lf",&city[i].x,&city[i].y);
		for(int i = 1; i <= m; i++)
			scanf("%lf%lf",&base[i].x,&base[i].y);
		int q;
		scanf("%d",&q);
		while(q--)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			printf("%d\n",find(city[x],city[y]));
		}
	}
	return 0;
}


你可能感兴趣的:(计算几何)