解题思路:暴力枚举。每次先枚举出2个点。作为直线。再去枚举第三个点看在不在直线上。 利用直线的斜率计算公式,假设三个点,a(x1,y1) , b(x2,y2) , c(x3,y3) ,当(y2-y1)/(x2-x1)=(y3-y2)/(x3-x1) 时,说明共线。
注意:本题输入有坑,未指明什么时候输入结束,因此不能用普通的scanf输入,应用sscanf, 从一个字符串中读进与指定格式相符的数据。且输入m(测试案例数)后,需要在输一个换行,因下边是字符串录入,因此要用两个getchar()来接收。详情见代码中注释,都已标明。
Description
Lining Up
Lining Up |
``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 begins with a single positive integer on a line by itself indicating the number of the cases following, each of them as described below. This line is followed by a blank line, and there is also a blank line between two consecutive inputs.
The input consists of N pairs of integers, where 1 < N < 700. Each pair of integers is separated by one blank and ended by a new-line character. The list of pairs is ended with an end-of-file character. No pair will occur twice.
Output
For each test case, the output must follow the description below. The outputs of two consecutive cases will be separated by a blank line.
The output consists of one integer representing the largest number of points that all lie on one line.
Sample Input
1 1 1 2 2 3 3 9 10 10 11
Sample Output
3
我的代码:
<span style="font-family:SimHei;font-size:18px;">#include<stdio.h>
#include<string.h>
int main()
{
int t,m,num,i,j,k;
int a[50000],b[50000];
char s[100];
scanf("%d",&m);
getchar();//输完m后的第一个enter键
getchar();//下一个换行
while(m--)
{
i=0;
while(gets(s))
{
if(!strlen(s))
break;
sscanf(s,"%d %d",&a[i],&b[i]);//不能a[i++],b[i++],这样每输一组数,i相当于自加两次
i++;
}
t=i;
int max=0;
for(i=0; i<t; i++)
{
for(j=i+1; j<t; j++)
{
num=0;
for(k=j+1; k<t; k++)
{
if((a[i]-a[k])*(b[i]-b[j])==(a[i]-a[j])*(b[i]-b[k]))//判断斜率是否相等
num++;
}
if(num>max)
max=num;
}
}
printf("%d\n",max+2);//从第三组数据开始计算看是否跟前两组数据构成的直线共线
if(m) //每两组输出数据之间有一个换行
printf("\n");
}
return 0;
}
</span>