题意:输入几个点,输出最多有几个点在一条直线上。
方法:枚举所有点与其他点的斜率,取斜率相同最多的情况。时间复杂度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是把所有的斜率都列出来排序,错误!