Convex packet Problem--graham Scan

Source: Internet
Author: User

Graham Scan Overview:

The definition of convex polygon is not described in detail here, the implementation principle of the algorithm is given here.

Step 1:

Find the set of points with the lowest x value, and find the point with the lowest Y value as the initial point

Step 2:

After acquiring a new sequence, p[n]=p[1]

Step 3:

Put p[0],p[1],p[2] into a stack, from i=3 Loop to i=n-1, take stack top two elements and P[i] line, if not formed left-hand, stack top element back stack, until the stack of elements only two left.

Press P[i] into the stack.

C + + code:

#include <algorithm>#defineMax_n 100000000intTop//number of vertices in convex hulltypedef std::p air<int,int>Point ;intDis (point p1, point p2)//The square of the distance of two points{    return(P1.first-p2.first) * (P1.first-p2.first) + (p1.second-p2.second) * (P1.second-p2.second);} Point P[max_n];//cross product of vector p0p1 and vector p0p2intmulti (Point P1, point P2, point p0) {//x1*y2-x2*y1    return(P1.first-p0.first) * (P2.second-p0.second)-(P2.first-p0.first) * (P1.second-p0.second);}BOOLCMP (Point A, point B) {//Point B has a greater angle.    if(multi (A, B, p[0]) >0)        return true; //co-line    if(multi (A, B, p[0]) ==0&& Dis (A, p[0]) < dis (b, p[0]))        return true; return false;}//the essence of Graham_scanvoidGraham_scan (Point p[], point stack[],intN) {    intI, k =0; Top=2; //find the bottom and left point     for(i =1; I < n;i++)        if(P[i].second < P[k].second | | (P[i].second = = P[k].second) && (P[i].first <P[k].first)))  K=i; //Specify the point as p[0];Std::swap (p[0], p[k]); //Sort by polar angle from small to large, short distances, note p[0]Std::sort (p[1], P[n-1], CMP); //Core, for convenience, use our self-built stackstack[0] = p[0], stack[1] = p[1], stack[2] = p[2];  for(i =3; I < n;i++)    {         while(Top >1&& multi (P[i], stack[top], stack[top-1]) >=0) Top--; stack[++top] =P[i]; }} 

Convex packet Problem--graham Scan

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.