(Relax ST1.13)POJ 2780 Linearity(给出若干个点,求最多有多少个点共线,不能使用n^3算法)

本文介绍了一种通过计算斜率来寻找二维平面上共线点对的算法,并详细展示了如何利用C++实现该算法的过程。通过对输入点集进行排序并计算所有可能的斜率,该算法能够找出具有相同斜率的最大点对集合。

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


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>


using namespace std;

const int maxn = 1010;
const int inf = INT_MIN;
struct Point{
	int x;
	int y;

	bool operator<(const Point& b)const{//排序规则这里怎么定义都无所谓,但是一定要定义。。。
		if(x == b.x){
			return y < b.y;
		}

		return x < b.x;
	}
}p[maxn];

double cal(const Point& a,const Point& b){
	if(b.x == a.x){
		return inf;
	}

	return (b.y - a.y)*1.0/(b.x - a.x);
}

int main(){
	int n;
	while(scanf("%d",&n)!=EOF){
		int maxm = -10;

		double xielv[maxn*2];

		int i;
		for(i = 0 ; i < n ; ++i){
			scanf("%d%d",&p[i].x,&p[i].y);
		}

		sort(p,p+n);
		int j;
		for(i = 0 ; i < n-1 ; ++i){
			int index = 0;
			for(j = i+1 ; j < n ; ++j){
				xielv[index++] = cal(p[i],p[j]);
			}

			sort(xielv,xielv+index);//对斜率进行排序....


            /**
             * 将斜率数组排序以后,这时候可能就会出现这么一种情况,
             * 前后可能有好几个斜率是一样的...
             * 以下就是数这样的斜率线每段有多少个...
             */
			for(j = 0 ; j < index ; ++j){
				int count = 0;
				while(fabs(xielv[j] - xielv[j+1]) == 0){
					count++;
					j++;
				}

				maxm = (maxm>count)?maxm:count;
			}


		}

//		printf("%d\n",maxm+2);
		cout<<maxm+2<<endl;
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值