uva - 270 - Lining Up(枚举、排序)

本文介绍了一种解决多个点中找出共线点数量的最大值的方法。通过枚举每两个点计算斜率,并统计斜率相同的点数来实现。文章提供了完整的C++代码实现,包括输入点坐标、计算斜率及查找最大共线点数的过程。

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

题意:输入几个点,输出最多有几个点在一条直线上。

方法:枚举所有点与其他点的斜率,取斜率相同最多的情况。时间复杂度O(n^n)。

#include <iostream>  
#include <iomanip>  
#include <string>  
#include <cstring>  
#include <cstdio>  
#include <queue>  
#include <stack>  
#include <algorithm>  
#include <cmath>  

using namespace std;

#define MAX 700+10
struct Point
{
	int x;
	int y;
};

int n, _max = 2;
Point point[MAX];
double slope[300000];

void Input()
{
	char s[100];
	int k = 0;
	while (gets(s) != NULL && s[0] != '\0')
	{
		char  temp_1[100], temp_2[100];
		memset(temp_1, 0, sizeof(temp_1));
		memset(temp_2, 0, sizeof(temp_2));
		int i = 0, j = 0;
		for (i = 0; s[i] != ' '; i++)
			temp_1[j++] = s[i];
		for (i++, j = 0; i < strlen(s); i++)
			temp_2[j++] = s[i];
		point[n].x = atoi(temp_1);
		point[n].y = atoi(temp_2);
		n++;
	}
}

double Cal_Slope(Point a, Point b)
{
	return (double)(b.y - a.y)/(b.x - a.x);
}

int cmp(const void *a, const void *b)
{
	return *(double *)a > *(double *)b ? 1 : -1;
}

void Search(int k)
{
	int i = 0, count = 2;
	for (i = 1; i < k; i++)
	{
		if (slope[i] - slope[i-1] < 1e-10)
		{
			count++;
			if (count > _max)
				_max = count;
		}
		else
			count = 2;
	}
}

int main()
{
#ifdef Local  
	freopen("a.in", "r", stdin);  
#endif  
	int t = 0, i = 0, j = 0, k = 0;
	cin >> t;
	getchar(), getchar();
	while (t--)
	{
		memset(slope, 0, sizeof(slope));
		memset(point, 0, sizeof(point));
		_max = 2, n = 0;
		Input();
		if (2 == n)
			cout << "2" << endl;
		else
		{
			for (i = 0; i < n-1; i++)
			{
				k = 0;
				for (j = 0; j < n; j++)
					if(j != i)
						slope[k++] = Cal_Slope(point[i], point[j]);
				qsort(slope, k, sizeof(slope[0]), cmp);
				Search(k);
			}
			cout << _max << endl;
		}
		if (t)
			cout << endl;
	}
}


输出最小为2,WA在写成0了,第一次WA是把所有的斜率都列出来排序,错误!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值