【发布时间】: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