Linearity
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 8479 | Accepted: 1954 |
Description
Alice often examines star maps where stars are represented by points in a plane and there is a Cartesian coordinate for each star. Let the Linearity of a star map be the maximum number of stars in a straight line.
For example, look at the star map shown on the figure above, the Linearity of this map is 3, because the star 1, star 2, and star 5 are within the same straight line, and there is no straight line that passes 4 stars.
You are to write a program to find the Linearity of a star map.
For example, look at the star map shown on the figure above, the Linearity of this map is 3, because the star 1, star 2, and star 5 are within the same straight line, and there is no straight line that passes 4 stars.
You are to write a program to find the Linearity of a star map.
Input
Input will contain multiple test cases. Each describes a star map.
For each test case, the first line of the input contains the number of stars N (2 <= N <= 1000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0 <= X, Y <= 1000). There can be only one star at one point of the plane.
For each test case, the first line of the input contains the number of stars N (2 <= N <= 1000). The following N lines describe coordinates of stars (two integers X and Y per line separated by a space, 0 <= X, Y <= 1000). There can be only one star at one point of the plane.
Output
Output the Linearity of the map in a single line.
Sample Input
5 0 0 2 0 0 2 1 1 2 2
Sample Output
2
这道题目如果复杂度是n^3,那么肯定会TL,所以尽可能减少不必要的循环,可以先计算出一个点与其他所有点的鞋=斜率,对这些斜率进行排序,最后统计斜率一样的计数就可以。再取第二点,对此进行相同的操作,最后取完所有的点,选择出最大的数即为一条直线上的最多点的数目。
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
#define max(a,b) (a>b?a:b)
#define N 1002
#define INF 100000000;
int main()
{
int n;
double x[N],y[N];
double xielv[1002];
while(scanf("%d",&n))
{
int result=0;
for(int i=0;i<n;i++)
scanf("%lf %lf",&x[i],&y[i]);
int count=0;
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(x[i]-x[j]!=0)
xielv[count++]=(y[i]-y[j])/(x[i]-x[j]);
if(x[i]-x[j]==0)
xielv[count++]=INF;
}
sort(xielv,xielv+count);
int num=1,mx=0;
for(int j=0;j<count-1;j++)
{
if(xielv[j]==xielv[j+1])//相邻的斜率相同的话则计数
num++;
else
{
mx=max(mx,num);
mx=num;
num=1;
}
}
result=max(result,mx);//选择在所有的计数中最大的
}
cout<<result<<endl;
}
return 0;
}