POJ - 1696 Space Ant

博客围绕一个题目展开,n个点,蚂蚁从y坐标最小点逆时针爬行,每次选剩下点中最靠右的点,需写出经过点的序号。题解指出这是凸包变种问题,可用凸包求解,涉及卷包裹算法和极角排序,极角排序还涉及Granham Scan算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

n个点,蚂蚁从y坐标最小的点开始逆时针爬行,写出经过点的序号。

每次选点都只能从剩下的点中选择最靠右的,用叉积排序求解。题解有说这是凸包变种,可用凸包求解(写的时候没写对),涉及卷包裹算法,也可以用极角排序,涉及Granham Scan算法。

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=100;
const double inf=1e9;
const double eps=1e-8;

int sgn(double x){
	if(fabs(x)<eps)
		return 0;
	if(x<0)
		return -1;
	else return 1;
}

struct point{
	double x,y;
	int index;
	point(){}
	point(double sx,double sy):x(sx),y(sy){}
	point operator +(const point &w)const{  //相减 
		return point(x+w.x,y+w.y);
	}
	point operator -(const point &w)const{  //相减 
		return point(x-w.x,y-w.y);
	}
	double operator ^(const point &w)const{ //叉积 
		return x*w.y-y*w.x;
	}
	double operator *(const point &w)const{ //点积 
		return x*w.x+y*w.y;
	}
}p[N];

double dist(point a,point b){
	return sqrt((a-b)*(a-b));
}

int pos;
bool cmp1(point a,point b){
	double mp=(a-p[pos]^(b-p[pos]));
	if(sgn(mp)==0)
		return dist(p[pos],a)<dist(p[pos],b);
	else if(sgn(mp)<0)
		return false;
	else
		return true;
}

int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		int n;
		scanf("%d",&n);
	
		for(int i=0;i<n;i++){
			scanf("%d%lf%lf",&p[i].index,&p[i].x,&p[i].y);
			if(p[i].y<p[0].y||(p[i].y==p[0].y&&p[i].x<p[0].x))
				swap(p[0],p[i]);
		}
		
		pos=0;
		for(int i=1;i<n;i++){
			sort(p+i,p+n,cmp1);
			pos++;
		}
		
		printf("%d ",n);
		for(int i=0;i<n;i++)
			printf("%d%c",p[i].index,i==n-1?'\n':' ');
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值