Language:
Grandpa's Estate
Description
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 |
题意:给定一个凸包顶点中的几个顶点问由这几个顶点能否构成原凸包;
解题思路:将给定的顶点重新构建凸包当构建的凸包中有任意一条边不是三点及其以上共线时即不能确定原凸包;
因为当最后一个点不是顶点且该凸包为凸多边形所以当最后一个点没有加入凸包中时即可确定最后一个点和倒数第二个点共线即和起点共线所以不用判断起点和终点
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
struct point{
int x,y;
}A[1010],result[1010];
int dist(point a,point b){
return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
int cp(point p1,point p2,point p3){
return (p3.x-p1.x)*(p2.y-p1.y)-(p3.y-p1.y)*(p2.x-p1.x);
}
bool cmp(point a,point b){
int ans=cp(A[0],a,b);
if(ans==0)
return dist(A[0],a)-dist(A[0],b)<=0;
return ans>0;
}
bool judge(int top){
int i;
for(i=1;i<top;++i){
if(cp(result[i-1],result[i],result[i+1])!=0&&cp(result[i],result[i+1],result[i+2])!=0)return false;
}
return true;
}
int main()
{
int t,i,j,n;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
int pos=0;
for(i=0;i<n;++i){
scanf("%d%d",&A[i].x,&A[i].y);
if(A[pos].y>=A[i].y){
if(A[pos].y==A[i].y){
if(A[pos].x>A[i].x)pos=i;
}
else pos=i;
}
}
if(n<6){
printf("NO\n");
continue;
}
point temp;
temp=A[0];A[0]=A[pos];A[pos]=temp;
sort(A+1,A+n,cmp);int top=1;
result[0]=A[0];result[1]=A[1];
for(i=2;i<n;++i){
while(top>=1&&cp(result[top-1],result[top],A[i])<0)top--;
result[++top]=A[i];
}
if(judge(top))
printf("YES\n");
else
printf("NO\n");
}
return 0;
}