Problem
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.
思路
计算几何题。从一点到另一点的过程中,不断二分即可。
代码
#include<bits/stdc++.h>
#define eps 1e-8
using namespace std;
struct Point {
double x, y;
Point() {};
Point(double _x, double _y) :x(_x), y(_y) {};
double Dist(const Point p) {
return sqrt((x - p.x)*(x - p.x) + (y - p.y)*(y - p.y));
}
Point Mid(const Point p) {
return Point((x + p.x) / 2, (y + p.y) / 2);
}
friend istream& operator>>(istream& is, Point &p) {
is >> p.x >> p.y;
return is;
}
};
Point c[55], s[55];
int n, m, t, a, b;
void Init() {
memset(c, 0, sizeof(c));
memset(s, 0, sizeof(s));
}
int Search(Point p) {
int res = 1;
double min_dist = p.Dist(s[1]);
for (int i = 2; i <= m; i++) {
double dist = p.Dist(s[i]);
if (dist<min_dist) { res = i; min_dist = dist; }
}
return res;
}
int Solve(Point a, Point b) {
int p = Search(a), q = Search(b);
if (p == q)return 0;
else if (a.Dist(b)<eps)return 1;
else {
Point mid = a.Mid(b);
return Solve(a, mid) + Solve(mid, b);
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
while (cin >> n >> m) {
Init();
for (int i = 1; i <= n; i++)cin >> c[i];
for (int i = 1; i <= m; i++)cin >> s[i];
cin >> t;
while (t--) {
cin >> a >> b;
cout << Solve(c[a], c[b]) << endl;
}
}
return 0;
}