📌  相关文章
📜  使用给定点找到距原点的最大可能距离

📅  最后修改于: 2021-04-29 15:33:08             🧑  作者: Mango

给定N个二维点。任务是使用给定点找到距原点的最大可能距离。使用第i(x i ,y i )可以从(a,b)移到(a + x i ,b + y i )
注意: N介于11000之间,每个点最多可以使用一次。

例子:

方法:主要观察结果是,当按点的方向将它们的向量与x轴形成的角度排序时,答案将包括某个连续范围内的向量。可以从这里阅读这一事实的证明。然后,该解决方案非常容易实现。迭代所有可能的范围,并为每个范围计算答案,以最大值作为结果。如果实施得当,这是一种O(N 2 )方法。

下面是上述方法的实现:

// C++ implementation of the approach
#include 
using namespace std;
  
// Function to find the maximum possible
// distance from origin using given points.
void Max_Distance(vector >& xy, int n)
{
    // Sort the points with their tan angle
    sort(xy.begin(), xy.end(), [](const pair& l,
                                  const pair& r) {
        return atan2l(l.second, l.first)
               < atan2l(r.second, r.first);
    });
  
    // Push the whole vector
    for (int i = 0; i < n; i++)
        xy.push_back(xy[i]);
  
    // To store the required answer
    int res = 0;
  
    // Find the maximum possible answer
    for (int i = 0; i < n; i++) {
        int x = 0, y = 0;
        for (int j = i; j < i + n; j++) {
            x += xy[j].first;
            y += xy[j].second;
            res = max(res, x * x + y * y);
        }
    }
  
    // Print the required answer
    cout << fixed << setprecision(2) << sqrtl(res);
}
  
// Driver code
int main()
{
    vector > vec = { { 1, 1 },
                                    { 2, 2 },
                                    { 3, 3 },
                                    { 4, 4 } };
  
    int n = vec.size();
  
    // Function call
    Max_Distance(vec, n);
  
    return 0;
}
输出:
14.14