How am I ever going to solve this problem?” said the pilot.
Indeed, the pilot was not facing an easy task. She had to drop packages at specific points scattered in a dangerous area. Furthermore, the pilot could only fly over the area once in a straight line, and she had to fly over as many points as possible. All points were given by means of integer coordinates in a two-dimensional space. The pilot wanted to know the largest number of points from the given set that all lie on one line. Can you write a program that calculates this number?
Your program has to be efficient!
Input
The input consists of multiple test cases, and each case begins with a single positive integer on a line by itself indicating the number of points, followed by N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. No pair will occur twice in one test case.
Output
For each test case, the output consists of one integer representing the largest number of points that all lie on one line, one line per case.
Sample Input
5
1 1
2 2
3 3
9 10
10 11
Sample Output
3
直接枚举就可以
代码
#include<bits/stdc++.h>
using namespace std ;
typedef long long LL ;
const int MAXN = 700+10 ;
const int MAXM = 1e5 ;
const int mod = 1007 ;
struct Node{
int x,y;
}node[MAXN];
int main(){
int n;
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++) {
int x,y;scanf("%d%d",&x,&y);
node[i]={x,y};
}
int ans=-1;
for(int i=1;i<=n;i++){// 一开始就想着用斜率了,所以要考虑下斜率不存在的情况。
int cnt=0;int num=0;
for(int j=1;j<=n;j++){
if(node[i].x==node[j].x) cnt++;
if(node[i].y==node[j].y) num++;
}
ans=max(ans,cnt);
ans=max(ans,num);
}
// printf("%d\n",ans);
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(node[i].x==node[j].x||node[i].y==node[j].y) continue;
double k=(node[j].y-node[i].y)*1.0/(node[j].x-node[i].x);//枚举任意两个点之间的斜率
int cnt=2; //printf("k==%.3lf\n",k);
for(int z=j+1;z<=n;z++){ // 这里从头开始暴力会TLE 。其实不用,稍微想一下就知道了。
double s=node[j].y+k*(node[z].x-node[j].x);
if(fabs(node[z].y*1.0-s)<1e-6) cnt++;
}
ans=max(ans,cnt);
}
}
printf("%d\n",ans);
}
return 0;
}
其实不用上述的这么麻烦,三点共线的话,虽然是用到斜率(可能会有斜率不存在的情况),但是我们可以将公式变形一下(数学老师肯定都讲过,但是我却没有想起来TAT) 将除换为乘 ,就不用考虑斜率不存在的问题了。
比如 A B C 三点
(ay-by)/(ax-bx) == (ay-cy)/(ax-cx)
转化 为 (ay-by)(ax-cx) == (ax-bx)(ay-cy)
代码
#include<bits/stdc++.h>
using namespace std ;
typedef long long LL ;
const int MAXN = 700+10 ;
const int MAXM = 1e5 ;
const int mod = 1007 ;
struct Node{
int x,y;
}node[MAXN];
bool check(Node a,Node b,Node c) {
return (a.y-b.y)*(a.x-c.x) == (a.x-b.x)*(a.y-c.y) ;
}
int main(){
int n;
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++) {
int x,y;scanf("%d%d",&x,&y);
node[i]={x,y};
}
int ans=-1;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
int cnt=2;
for(int z=j+1;z<=n;z++){ // 这里从头开始暴力会TLE 。其实不用,稍微想一下就知道了。
if(check(node[i],node[j],node[z])) cnt++;
}
ans=max(ans,cnt);
}
}
printf("%d\n",ans);
}
return 0;
}