这个问题是关于从一堆点中找到共线点。
首先,我不了解slopeMap
和无序地图如何?映射不是仅假定具有键和值(map<key, value>
)吗?在此特定代码中
unordered_map<pair<int, int>, int,boost::
hash<pair<int, int> > > slopeMap;
据我所知,它具有一对作为键,其后有一个int,应该是值,但是那不就到此为止了吗?
完整代码:
using namespace std;
// method to find maximum colinear point
int maxPointOnSameLine(vector< pair<int, int> > points)
{
int N = points.size();
if (N < 2)
return N;
int maxPoint = 0;
int curMax, overlapPoints, verticalPoints;
// here since we are using unordered_map
// which is based on hash function
//But by default we don't have hash function for pairs
//so we'll use hash function defined in Boost library
unordered_map<pair<int, int>, int,boost::
hash<pair<int, int> > > slopeMap;
// looping for each point
for (int i = 0; i < N; i++)
{
curMax = overlapPoints = verticalPoints = 0;
// looping from i + 1 to ignore same pair again
for (int j = i + 1; j < N; j++)
{
// If both point are equal then just
// increase overlapPoint count
if (points[i] == points[j])
overlapPoints++;
// If x co-ordinate is same, then both
// point are vertical to each other
else if (points[i].first == points[j].first)
verticalPoints++;
else
{
int yDif = points[j].second - points[i].second;
int xDif = points[j].first - points[i].first;
int g = __gcd(xDif, yDif);
// reducing the difference by their gcd
yDif /= g;
xDif /= g;
// increasing the frequency of current slope
// in map
slopeMap[make_pair(yDif, xDif)]++;
curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]);
}
curMax = max(curMax, verticalPoints);
}
// updating global maximum by current point's maximum
maxPoint = max(maxPoint, curMax + overlapPoints + 1);
// printf("maximum colinear point
// which contains current point
// are : %d\n", curMax + overlapPoints + 1);
slopeMap.clear();
}
return maxPoint;
}
//驱动程序代码
int main()
{
const int N = 6;
int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2},
{3, 3}, {3, 4}};
vector< pair<int, int> > points;
for (int i = 0; i < N; i++)
points.push_back(make_pair(arr[i][0], arr[i][1]));
cout << maxPointOnSameLine(points) << endl;
return 0;
}
位置
Input : points[] = {-1, 1}, {0, 0}, {1, 1},
{2, 2}, {3, 3}, {3, 4}
Output : 4
Then maximum number of point which lie on same
line are 4, those point are {0, 0}, {1, 1}, {2, 2},
{3, 3}
我还想要一个基于逻辑的建议。我该如何修改此代码,而不是返回定义共线性的最大点数的数字,而是以某种形式的数据结构实际存储共线性的任何点,以便以后使用?
答案 0 :(得分:0)
地图不是仅假定具有键和值(地图)吗?
实际上,std::unordered_map还有几个附加的模板参数。第三个参数是哈希。
我该如何修改此代码,而不是返回数字 定义共线的最大点数,以实际存储任何 我可以使用的某种形式的数据结构中共线的点 以后吗?
使用整数坐标比使用浮点数更容易(由于精度问题)。我假设您有一个二维点p
的数组。一种方法是,对于每两对点p[i]
和p[j]
,让您的密钥为对dX,dY 简化为最低形式(其中{{1} }和dX = p[j].x - p[i].x
)。那么您的值可以是dY = p[j].y - p[i].y
,其中包含匹配的索引std::set<int>
和i
。