题目链接:
题目大意:
平面 n 个点,求凸包的周长。
数据范围:
解题思路:
凸包板子题。
这里说一下
Graham
扫描法。
准备工作:将所有点排序,找到一个最下且最左的点,这个点一定在凸包上(一想就是那样)。以这个点为原点,令为
P1
,对其余的点进行极角排序。所谓极角,就是一个点与原点的连线与
x
轴所成的夹角。若多个点极角相等,则靠近原点的点在前。先后将原点
令栈顶那个点为
T
,栈顶的下一个点为
2 . 将
Pi
压入栈中,
3 . 先将栈顶元素删除,再判断
Pi
在 当前栈顶元素
T′
和栈顶下一个元素
t′
连线 的左边还是右边,在右边则再删除栈顶元素,继续判断;直到
Pi
在左边为止,将其压入栈中。
如果到了第
n
个点,直接压入栈中,结束算法。因为极角排序之后的最后一个点一定在凸包上。
去copy了一个不错的动图:
一个不错的blog:link
详见代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
#include <set>
#include <map>
using namespace std;
typedef long long LL;
const int inf = 1 << 30;
const LL INF = 1LL << 60;
const int MaxN = 105;
const double eps = 1e-6;
int T;
int n, top;
struct Point {
int x, y;
int id;
Point () {}
Point (int a, int b) {
x = a; y = b;
}
bool friend operator < (const Point a, const Point b) {
if(a.y == b.y) return a.x < b.x;
else return a.y < b.y;
}
bool friend operator == (const Point a, const Point b) {
return (a.x == b.x) && (a.y == b.y);
}
Point friend operator + (const Point a, const Point b) {
return Point(a.x + b.x, a.y + b.y);
}
Point friend operator - (const Point a, const Point b) {
return Point(a.x - b.x, a.y - b.y);
}
}PP[MaxN + 5];
Point hull[MaxN + 5]; //存放凸包的数组
typedef Point Vector; //向量和点一样,都有x、y元素,所以这里就偷了个懒
int Dis(Point A, Point B) {
return (A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y);
}
double dis(Point A, Point B) { //两点的距离
return sqrt(1.0 * Dis(A, B));
}
int Cross(Vector A, Vector B) { //叉积
return A.x * B.y - A.y * B.x;
}
bool Gcmp(Point A, Point B) { //按照极角从大到小排序
Point O = PP[1]; //最下方的点一定在凸包上,将其作为原点进行极角排序
int tmp = Cross(A - O, B - O);
//向量OA和OB的叉积
//其实也可以直接写成Cross(A - O, B - O),那样写只是为了便于理解
if(tmp == 0) { //叉积为0,共线;所以离原点近的排在前面
if(Dis(A, O) < Dis(B, O)) return true;
else return false;
}
else { //不为0,不共线
if(tmp > 0) return true; //大于0,说明向量OB在向量OA的左边,所以OA排在前面
else return false; //反之,OB排在前面
}
}
void Graham() { //求凸包
sort(PP + 1, PP + n + 1); //排序找出最下方的点,作为原点
sort(PP + 2, PP + n + 1, Gcmp); //对其余的点进行极角排序
hull[1] = PP[1];
hull[2] = PP[2];
top = 2;
for(int i = 3; i <= n; i++) {
while(top >= 2 && Cross(hull[top] - hull[top - 1], PP[i] - hull[top - 1]) <= 0)
top--;
hull[++top] = PP[i];
}
}
void debug() {
printf("top = %d\n", top);
for(int i = 1; i <= top; i++)
printf("%d %d\n", hull[i].x, hull[i].y);
printf("\n");
}
int main()
{
while(scanf("%d", &n) != EOF)
{
if(n == 0) break;
top = 0;
for(int i = 1; i <= n; i++) {
scanf("%d %d", &PP[i].x, &PP[i].y);
}
Graham();
//debug();
double ans = 0.0;
if(n == 2) ans = dis(PP[1], PP[2]);
else if(n > 2){
for(int i = 2; i <= top; i++)
ans += dis(hull[i], hull[i - 1]);
ans += dis(hull[1], hull[top]);
}
printf("%.2lf\n", ans);
}
return 0;
}
这里还有一道凸包的题:link