此题就是判断在一些点中,最多有几个点可以成一条线。
思路就是找2个点,这2点肯定能成一条线,再找后面的点,做叉乘等于0就++,估计是UVA测试数据太弱,我本来想找到3个点能成一条线就把最后一个点给标记了,然后下次就不访问这个点,事实是这样是会遗漏最优解的。。但竟然能AC
看了别人的解题报告去学习了下极角排序,就是把一个点作为原点,然后对其他的点进行极角排序,这样只需要一次扫描就可以求出有这个点的线上最大点数,具体做法是不断的判断前一个和现在这个的叉积是否为0,是的话,K++,不是的话K=0。做的过程中我犯了一个极其愚蠢的错误,导致WA数次,这个错误是,先选出第一个点,然后进行极角排序,再选出第二个点,再极角排序,看似没有问题,其实问题在于排序后点的位置都换了,选的第二个点不是原来的第二个点了,就会有遗漏以及重复的问题。我调了好久才发觉这个问题。。至于效率比暴力优化在哪里呢?暴力是选2个点,再去选第三个点,所以是o(n^3),而极角排序的是先选一个点,再进行排序,排序完再遍历所有点一次所以时间复杂度是o(n^2log(n) + n^2)就是o(n^2log(n))。
暴力AC代码:
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<ctime>
using namespace std;
#define NMAX 50000
#define ll long long
struct node
{
int x,y;
}node[701];
inline bool on_one_line(struct node n1,struct node n2,struct node n3)
{
return (n3.x-n1.x)*(n3.y-n2.y)-(n3.y-n1.y)*(n3.x-n2.x) == 0;
}
int main()
{
// freopen("input.txt","r",stdin);
// freopen("o1.txt","w",stdout);
int i,j,k,n;
scanf("%d\n",&n);
while(n--)
{
char temp[100];
int nct = 0;
while(gets(temp) != NULL)
{
if(temp[0] == '\0') break;
sscanf(temp,"%d %d",&node[nct].x,&node[nct].y);
nct++;
}
int ans = 0;
for(i = 0; i < nct; i++)
for(j = i+1; j < nct; j++)
{
int count = 0;
for(k = j+1; k < nct; k++)
if(on_one_line(node[i],node[j],node[k]))
count++;
ans = max(ans,count);
}
printf("%d\n",ans+2);
if(n != 0) printf("\n");
}
return 0;
}
极角排序AC代码:
#include<cstdio>
#include<ctype.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<ctime>
using namespace std;
#define NMAX 50000
#define ll long long
#define eps 1e-8
typedef struct node
{
int x,y;
}pnode;
pnode node[705];
int nct;
int quad(pnode a)//判断象限函数
{
if(a.x>0 && a.y>=0) return 1;
if(a.x<=0 && a.y>0) return 2;
if(a.x<0 && a.y<=0) return 3;
if(a.x>=0 && a.y<0) return 4;
return 5;//把要(0,0)放在最后
}
int cmp(const void *a, const void *b)
{
pnode *t1 = (pnode*)a;
pnode *t2 = (pnode*)b;
pnode p1,p2,&temp = node[nct];
p1.x = t1->x-temp.x; p1.y = t1->y-temp.y;
p2.x = t2->x-temp.x; p2.y = t2->y-temp.y;
int l1,l2;
l1 = quad(p1); l2 = quad(p2);
if(l1 == l2)
{
int ans = p2.x*p1.y - p2.y*p1.x;
return ans;
}
return l1 - l2;
}
int main()
{
// freopen("input.txt","r",stdin);
// freopen("o1.txt","w",stdout);
int i,j,n;
scanf("%d\n",&n);
while(n--)
{
char temp[100];
nct = 0;
while(gets(temp))
{
if(temp[0] == '\0') break;
sscanf(temp,"%d %d",&node[nct].x,&node[nct].y);
nct++;
}
int ans = 0,k;
for(i = 0; i < nct; i++)
{
pnode t1[nct+1];
memcpy(t1,node,nct*sizeof(node[0]));//复制出来
node[nct] = node[i];
qsort(node,nct,sizeof(node[0]),cmp);
pnode &p = node[nct];
k=0;
for(j = 1; j < nct-1; j++)
{
pnode &p1 = node[j-1],&p2 = node[j];
if(((p1.x-p.x)*(p2.y-p.y) - (p2.x-p.x)*(p1.y-p.y)) == 0)
k++;
else
{
if(k > ans) ans = k;
k = 0;
}
}
if(k > ans) ans = k;
memcpy(node,t1,nct*sizeof(node[0]));//复制回去
}
printf("%d\n",ans+2);
if(n != 0) printf("\n");
}
return 0;
}