我正在寻找一种找到面积最大的四边形的方法。我已经计算了凸包的点数并将它们顺时针排序。我试过蛮力,但当然太慢了。所以我在这里找到了最大三角形的算法:
How to find largest triangle in convex hull aside from brute force search
它看起来非常好,所以我试图重拍它。我有通过将它分成两个三角形来计算任何四边形区域的函数(在这个函数中我正在对输入点进行排序以确保我正在计算直角三角形)。这是:
int n = convexHull.size();
int A = 0; int B = 1; int C = 2; int D = 3;
int bestA = A; int bestB = B; int bestC = C; int bestD = D;
while(true) { // loop A
while(true) { // loop B
while(true) { // loop C
while(quadrangleArea(A, B, C, D) <= quadrangleArea(A, B, C, (D+1)%n) ) { // loop D
D = (D+1)%n;
}
if(quadrangleArea(A, B, C, D) <= quadrangleArea(A, B, (C+1)%n, D) ) {
C = (C+1)%n;
continue;
}
else break;
}
if(quadrangleArea(A, B, C, D) <= quadrangleArea(A, (B+1)%n, C, D) ) {
B = (B+1)%n;
continue;
}
else break;
}
if(quadrangleArea(A, B, C, D) > quadrangleArea(bestA, bestB, bestC, bestD) ) {
bestA = A; bestB = B; bestC = C; bestD = D;
}
A = (A+1)%n;
if (A==B) B = (B+1)%n;
if (B==C) C = (C+1)%n;
if (C==D) D = (D+1)%n;
if (A==0) break;
}
它看起来很好,并且为我的简单测试提供了很好的结果,但我担心有些事情是不对的。通过这种推理,我可以为每个具有n个顶点的多边形制作算法 - 但凭直觉我觉得这是不可能的。我是对的吗?
我正在尝试解决有关spoj的"SHAMAN"问题,而我的回答是错误的。我99%肯定我的程序的其余部分都没问题,所以上面的代码有问题。你能帮我改进一下吗?也许你有一些棘手的测试可以证明这个算法不能正常工作?我会很感激任何提示!
答案 0 :(得分:0)
我将凸包分为两半,找到每一半中最大的三角形,计算总和 - 然后在凸包上旋转“分隔线”。像这样:
size_t n = convexHull.size();
size_t A = 0;
size_t B = n/2;
size_t C, D;
size_t maxarea = 0;
size_t area;
size_t maxQuad[4];
// size_t findLargestTriangle(convHullType c, int& tip);
// make this search the hull "c" with the assumption
// that the first and last point in it form the longest
// possible side, and therefore will be base of the
// triangle with the largest area. The "other" point
// will be returned, as will be the size.
while (A < n/2 && B < n) {
// this is partially pseudocode, as you need to treat
// the container as "circular list", where indices wrap
// around at container.size() - i.e. would have
// to be container[n + x] == container[n]. No ordinary
// C++ std:: container type behaves like this but it's
// not too hard to code this.
// This simply says, "two sub-ranges".
area =
findLargestTriangle(convexHull[A..B], C) +
findLargestTriangle(convexHull[B..A], D);
if (area > maxarea) {
maxarea = area;
maxQuad = { A, B, A + C, B + D };
}
A++; B++;
}
我不是一个很好的数学家,因此不能完全确定(无法证明)你可以像这样一起轮换A
和B
。希望有人可以填补这个空白...总是渴望自学; - )