I stumbled across this problem :
"A tourist have a map of dimensions M x N. On the map are plased k cities (k<=2000). Cities' coordinates have that form (lin, col) (lin<=M and col<=N). We know the tourist's coordinates as well. The tourist decided to take in a certain direction and to stop at the edge of the map. But he wants to walk on the direction that makes him walk through as many cities as posible. You have to calculate the maximum number of cities that he can visit."
M, N <= 1000
K<=2000
e.g. 5 10 (M and N)
3 2 (tourist's coordinates)
7 (k = number of cities)
0 0 (coordinates of the cities)
0 8
1 6
2 2
2 4
3 7
4 5
Answer : 3
Actually, the problem requires the maximum number of collinear points that includes the tourist coordonates.
I've found a solution that is O(k^2).
for(i=0; i<k; i++) {
fscanf(fi, "%d%d", &lin[i], &col[i]);
lin[i]-=l; //we consider tourist's coordinates the origin
col[i]-=c;
}
for(i=0; i<k; i++) {
points=1;
for(j=0; j<k; j++) {
...
if(lin[i] * col[j] == lin[j] * col[i]) //verify collinearity
points++;
...
}
But I'm pretty sure that it can be done better than O(k^2). I didn't find any optimizations yet.
答案 0 :(得分:3)
您可以计算由旅行者和每个点的坐标确定的线的斜率。你现在有一系列的斜坡。您现在可以订购此阵列,并查看出现次数最多的斜率。或者你可以散列斜率(以避免对数组进行排序)。
答案 1 :(得分:2)
您可以在O(n)中执行此操作。将旅游者的坐标定义为原点,如果线(t,k1)和(t,k2)具有相同的斜率,则两个城市k1和k2是共线的。如果将k值以斜率存储在哈希中,则只需要通过所有k一次,然后通过计算的斜率一次以找到具有最多ks的斜率。