1. 程式人生 > >【凸包 穩定凸包問題】POJ

【凸包 穩定凸包問題】POJ

Being the only living descendant of his grandfather, Kamran the Believer inherited all of the grandpa's belongings. The most valuable one was a piece of convex polygon shaped farm in the grandpa's birth village. The farm was originally separated from the neighboring farms by a thick rope hooked to some spikes (big nails) placed on the boundary of the polygon. But, when Kamran went to visit his farm, he noticed that the rope and some spikes are missing. Your task is to write a program to help Kamran decide whether the boundary of his farm can be exactly determined only by the remaining spikes.

Input

The first line of the input file contains a single integer t (1 <= t <= 10), the number of test cases, followed by the input data for each test case. The first line of each test case contains an integer n (1 <= n <= 1000) which is the number of remaining spikes. Next, there are n lines, one line per spike, each containing a pair of integers which are x and y coordinates of the spike.

Output

There should be one output line per test case containing YES or NO depending on whether the boundary of the farm can be uniquely determined from the input.

Sample Input

1
6 
0 0
1 2
3 4
2 0
2 4 
5 0

Sample Output

NO

給你n個點,問你這n個點能不能構成一個穩定凸包

很容易得到,當一個凸包穩定時,凸包的每條邊上都要有至少三個點,若只有兩個點,則可以增加一個點,得到更大的凸包。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=10005;
struct point
{
    double x,y;
}p[maxn],ans[maxn],minp;
int top;

double dist(point a,point b)
{
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

double cross(point a,point b,point c)  //叉積
{
    return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}

bool cmp(point a,point b)  //極角排序
{
    double k=cross(minp,a,b);
    if(k>0) return 1;
    if(k<0) return 0;
    return dist(minp,a)<dist(minp,b);
}

void graham(int n)
{
    minp=p[0];
    sort(p+1,p+n,cmp);
    ans[0]=p[0],ans[1]=p[1];
    top=1;
    for(int i=2;i<n;i++)
    {
        while(cross(ans[top-1],ans[top],p[i])<0&&top>=1) top--;
        ans[++top]=p[i];
    }
}

bool judge()
{
    for(int i=1;i<top;i++)
    {
        if((cross(ans[i-1],ans[i+1],ans[i]))!=0&&(cross(ans[i],ans[i+2],ans[i+1]))!=0)
            return false;
    }
    return true;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int n,pos=0;
        scanf("%d",&n);
        for(int i=0;i<n;i++)
        {
            scanf("%lf%lf",&p[i].x,&p[i].y);
            if(p[pos].y>=p[i].y)
            {
                if(p[pos].y==p[i].y)
                {
                    if(p[pos].x>p[i].x) pos=i;
                }
                else pos=i;
            }
        }
        swap(p[pos],p[0]);
        if(n<6)
        {
            printf("NO\n");
            continue;
        }
        graham(n);
        if(judge()) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}