【发布时间】:2023-03-20 14:50:01
【问题描述】:
我给了分数(a, b),然后我给了分数(x, 0)。
现在,对于每个点 (x, 0),我用所有点 (a, b) 画线(见图)。
对于每个点(x, 0),我必须返回这些点的索引/点(a, b)
通过该点/点和点(x, 0) 的直线的哪个y 截距最大。
点 (x, 0) 的所有 x 值都大于最大值 a。数字a, b, x 是正整数。
例子:
输入
3 4 (number of (a, b) points and number of (x, 0) points - let's call them m and n)
5 3 (point A, index 0)
14 1 (point C, index 1)
10 2 (point B, index 2)
16 20 40 15 (x values of points (x, 0))
输出
1
0 2
0
1
我的解决方案:
int main() {
int m, n;
cin >> m >> n;
vector<pair<int, int>> pointsAB(m);
for (int i = 0; i < m; ++i) {
cin >> pointsAB[i].first >> pointsAB[i].second;
}
for (int j = 0; j < n; ++j) {
int currX;
double minSlope = 1.00;
vector<int> indexes;
cin >> currX;
for (int i = 0; i < m; ++i) {
int a = pointsAB[i].first, b = pointsAB[i].second;
double currSlope = -((double)b) / (currX - a);
if (currSlope < minSlope) {
indexes.clear();
minSlope = currSlope;
indexes.push_back(i);
}
else if (currSlope == minSlope) {
indexes.push_back(i);
}
}
cout << indexes[0];
for (int k = 1; k < indexes.size(); ++k) {
cout << " " << indexes[k];
}
cout << '\n';
}
return 0;
}
我对这个问题的解决方案具有时间复杂度 O(m * n) 但这对我来说似乎不是很有效。我的问题是这个问题可以用更好的时间复杂度解决吗?如何解决?
【问题讨论】:
-
那么您的解决方案是什么是?
m和n是什么意思?在此处发布代码。 -
@meowgoesthedog 好的,我添加了我的解决方案。
m是(a, b)坐标数,n是(x, 0)坐标数 -
为什么是循环?最大可能值是无穷大。从您的一组点中选择斜率最大的点。
标签: c++ algorithm math cartesian-coordinates