计算几何问题
凸包问题:
计算几何模板:
struct Point{
double x,y;
Point(){};
Point(double _x, double _y):x(_x),y(_y){}//初始化
Point operator - (const Point & B) const
{
return Point(x-B.x, y-B.y);
}
Point operator + (const Point &B) const
{
return Point(x+B.x,y+B.y);
}
double det(const Point A,const Point B)
{
return A.x*B.x+A.y*B.y;
}
}p[maxn], ch[maxn];
比较大小来排序
bool cmp(Point p1, Point p2)
{
return p1.x < p2.x||(p1.x == p2.x&&p1.y < p2.y);
}
int squarDist(Point A, Point B) /**距离的平方*/
{
return (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y);
}
double Cross(Point A, Point B) /**叉积*/
{
return A.x*B.y-A.y*B.x;
}
void ConvexHull() /** 求凸包 */
{
sort(p,p+n,cmp); /**先按照 x 从小到大排序, 再按照 y 从小到大排序*/
m = 0;
for(int i = 0; i < n; i++) // 从前往后找"下凸包"
{
while(m > 1 && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for(int i = n-2; i >= 0; i--) /**从后往前找"上凸包", 形成完整的封闭背包*/
{
while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
if(n > 1) m--; /** 起点重复*/
}
/**旋转卡壳模板*/
int rotating_calipers()
{
int q = 1;
int ans = 0;
ch[m] = ch[0]; /**凸包边界处理*/
for(int i = 0; i < m; i++) /**依次用叉积找出凸包每一条边对应的最高点*/
{
while(Cross(ch[i+1]-ch[i], ch[q+1]-ch[i]) > Cross(ch[i+1]-ch[i], ch[q]-ch[i]))
q = (q+1)%m; //利用平行四边形的同底比较高的大小来找到最远点
ans = max(ans, max(squarDist(ch[i], ch[q]), squarDist(ch[i+1], ch[q+1])));
}
return ans;
}