求任意个点的凸包问题

    凸包(Convex Hull)是一个计算几何(图形学)中的概念。
在一个 实数 向量空间 V中,对于给定集合X,所有包含X的 凸集 交集 S被称为X的凸包
X的凸包可以用X内所有点(X1,...Xn)的 线性组合 来构造.
在二维 欧几里得空间 中,凸包可想象为一条刚好包著所有点的橡皮圈。
用不严谨的话来讲,给定二维平面上的点集,凸包就是将最外层的点连接起来构成的凸多边型,它能包含点集中所有点的。

对概念还不了解的请百度,下面是源代码:

https://code.csdn.net/snippets/575284.git

// 凸包.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;


#define N 100


struct Point
{
 double x, y;
}P[N], S[N];


int n, top;


double Dis(const Point& p1, const Point& p2)
{
 return sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y)*1.0);
}


double Cross(const Point& p1, const Point& p2, const Point& p3, const Point& p4)
{
 return (p2.x - p1.x)*(p4.y - p3.y) - (p2.y - p1.y)*(p4.x - p3.x);
}


bool cmp(const Point& p1, const Point& p2)
{
 double C = Cross(P[0], p1, P[0], p2);
 return C ? C>0 : Dis(P[0], p1)<Dis(P[0], p2);
}


void Pole_Point()
{
 int id;
 Point pp = P[id = 0];
 for (int i = 1; i<n; i++)
 if (P[i].y < pp.y || P[i].y == pp.y && P[i].x < pp.x)
  pp = P[i], id = i;
 P[id] = P[0], P[0] = pp;
}


void Convex_Hull()
{
 Pole_Point();
 sort(P + 1, P + n, cmp);
 S[0] = P[0], S[top = 1] = P[1];
 for (int i = 2; i<n; i++)
 {
  while (top && Cross(S[top - 1], S[top], S[top], P[i]) <= 0)
   --top;
  S[++top] = P[i];
 }
}


int main()
{
 while (~scanf_s("%d", &n))
 {
  for (int i = 0; i<n; i++)
   scanf_s("%lf %lf", &P[i].x, &P[i].y);
  Convex_Hull();
  printf("输出为:\n");
  for (int i = 0; i <= top; i++)
   printf("%.6f %.6f\n", S[i].x, S[i].y);
 }
 return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值