【问题标题】:Given a pivot point, sort a set of points in increasing order of angle which they make with the pivot point给定一个枢轴点,按照它们与枢轴点所成角度的递增顺序对一组点进行排序
【发布时间】:2020-10-02 21:25:54
【问题描述】:

正如标题中所说,我们需要按角度升序对点进行排序。

我正在使用枢轴点和其他点进行叉积。 如果任意两点与枢轴点的叉积为正,则表示这两点按升序排列。

我无法找到这个想法的错误,但这不起作用。代码是:

//Here,a[0] is the pivot point.

//pivot is a global variable assigned to a[0].

vector<pair<int, int>>a(n);

sort(a.begin() + 1, a.end(), comp);

int comp(pair<int, int> x, pair<int, int> y) {
    int cross_product = crpd(pivot, x, y);

    if (cross_product >= 0)
        return 1;

    return 0;
}

int crpd(pair<int, int> a, pair<int, int> b, pair<int, int> c) {
    //y2*x1 - y1*x2
    int y2 = a.second - c.second;
    int x2 = a.first - c.first;
    int y1 = a.second - b.second;
    int x1 = a.first - b.first;
    int ans = x1 * y2 - x2 * y1;
    return ans;
}
Sample Input:

Pivot: (0,-4)

Points: [ (-5,0) , (-5,1) , (-4,2) , (-3,3) , (-1,4) , (5,0) , (4,-3) , (0,-4) , (-4,-3) ] 
Expected Output: [ (4,-3) , (5,0) , (-1,4) , (-3,3) , (-4,2) , (-5,1) , (-5,0) , (-4,-3) ]
Displayed Output: [ (-5,0) , (4,-3) , (5,0) , (-1,4) , (-3,3) , (-4,2) , (-5,1) , (-4,-3) ] 

如果有人在任何地方发现任何错误,请回答

【问题讨论】:

  • 是什么让您认为有错误?共享任何失败的输入以及预期的输出。
  • “正如问题中所说”——当这些是问题的第一句话时,我觉得这很难接受。也许您的意思是“如标题中所述”,并且出于某种原因认为将该信息复制到问题中以使问题自包含是一个坏主意?
  • long long ans = x1 * y2 - x2 * y1 你正在对 int 执行操作,所以你会得到一个 int。将操作数转换为 long long 以获得正确的结果。
  • @theWiseBro ,感谢您的建议,但即使返回类型是 int 我也会得到错误的输出。

标签: c++ algorithm math optimization convex-hull


【解决方案1】:

叉积“原样”仅给出角度符号,因为您的向量未标准化(单位长度)。除以向量的大小是朝着正确方向迈出的一步,但它给出了可能的角度范围-Pi/2..Pi/2

您可以使用atan2 获得可比较的值 - 全方位-Pi..Pi 的角度

angle = atan2(x1 * y2 - x2 * y1, x1 * x2 + y1 * y2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-10
    • 2018-03-05
    • 1970-01-01
    • 2012-09-08
    • 2016-09-07
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多