【计算几何/极角排序】 HRBUST 1305 多边形

多边形

Time Limit: 1000 MS Memory Limit: 65536 K

Description

一个封闭的多边形定义是被有限个线段包围。线段的相交点称作多边形的顶点,当你从多边形的一个顶点沿着线段行走时,最终你会回到出发点。

这里写图片描述

凸多边形(convex)想必大家已经很熟悉了,下图给出了凸多边形和非凸多边形实例。

这里讨论的是在平面坐标的封闭凸多边形,多变形的顶点一个顶点在原点(x=0,y=0).图2显示的那样。这样的图形有两种性质。
这里写图片描述

第一种性质是多边形的顶点会在平面上少于等于三个象限,就如图二那样,第二向县里面没有多边形的点(x<0,y>0)。

为了解释第二种性质,假设你沿着多边形旅行,从原点(0,0)出发遍历每个顶点一次,当你遍历到除原点(0,0)时候,从这一点画一条和原点(0,0)的斜线。计算这种斜率。当计算完所有的斜率时候,这些斜率组成升序或降序顺序。

如图三所示。

这里写图片描述

Input

输入包含多组测试数据。

第一行输入一个整数n(50>n>0),其中n表示多边形顶点的个数,当n为0时表示结束。紧跟n行输入在平面中多边形的顶点整数x,y(-999

Sample Input

10
0 0
70 -50
60 30
-30 -50
80 20
50 -60
90 -20
-30 -40
-10 -60
90 10
0

Sample Output

(0,0)
(-30,-40)
(-30,-50)
(-10,-60)
(50,-60)
(70,-50)
(90,-20)
(90,10)
(80,20)
(60,30)

Author

鲁学涛

题意

按照题目要求逆时针输出以原点为基准的极角排序。

思路

极角排序的一种方法
对于任意两个点p0,p1,算出其对于极点的向量a.b;
如果a叉乘b大于零,则b在a的逆时针方向,
否则则是顺时针方向。
如果叉乘等于零,说明共线或者重合,此时按照x的坐标从小到大排序即可。

坑点

全无

AC代码

#include<bits/stdc++.h>
using namespace std;

class Point{
public:
    double x,y;
    Point(double x = 0,double y = 0):x(x),y(y){}
    Point operator + (Point a) {return Point(x + a.x,y + a.y);}
    Point operator - (Point b) {return Point(x - b.x,y - b.y);}
};

Point aim(0,0);

typedef Point Vector ;
typedef vector<Point> Pol ;

double cross(Vector a,Vector b)
{
    return a.x*b.y - a.y*b.x;
}

bool cmp(Point p1,Point p2)
{
    Vector a = p1 - aim;
    Vector b = p2 - aim;
    double ans = cross(a,b);
    if(ans==0.0) return p1.x < p2.x;
    else return ans > 0.0;
}

void solve(void)
{
    int n;
    while(scanf("%d",&n)&&n)
    {
        Pol p;
        for(int i = 0 ; i < n ; i++)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            if(i!=0)
                p.push_back(Point(x,y));
        }
        sort(p.begin(),p.end(),cmp);
        printf("(0,0)\n");
        for(int i = 0 ; i < n-1 ; i++)
        {
            printf("(%.0lf,%.0lf)\n",p[i].x,p[i].y);
        }
    }
}

int main(void)
{
    solve();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/peng0614/article/details/81115416