点集中共线点的最大个数

来源:互联网 发布:数控车削国际象棋编程 编辑:程序博客网 时间:2024/04/30 07:38

http://acm.pku.edu.cn/JudgeOnline/problem?id=2606

Description
A good hunter kills two rabbits with one shot. Of course, it can be easily done since for any two points we can always draw a line containing the both. But killing three or more rabbits in one shot is much more difficult task. To be the best hunter in the world one should be able to kill the maximal possible number of rabbits. Assume that rabbit is a point on the plane with integer x and y coordinates. Having a set of rabbits you are to find the largest number K of rabbits that can be killed with single shot, i.e. maximum number of points lying exactly on the same line. No two rabbits sit at one point.

Input
An input contains an integer N (2<=N<=200) specifying the number of rabbits. Each of the next N lines in the input contains the x coordinate and the y coordinate (in this order) separated by a space (-1000<=x,y<=1000).

Output
The output contains the maximal number K of rabbits situated in one line.

Sample Input

 

Sample Output

5
方法1:
// Rabbit hunt.cpp : Defines the entry point for the console application.
// http://acm.pku.edu.cn/JudgeOnline/showproblem?problem_id=2606
// 遍历寻找
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
 short n,x[200],y[200];
 int i,j,k,max=0,num; 
 long a,b;
 cin>>n;
 for(i=0;i<n;i++) cin>>x[i]>>y[i];
 for(j=0;j<n-1;j++)
 {
  for(k=j+1;k<n;k++)
  {
   num=2;
   a=x[j]-x[k];b=y[j]-y[k];
   for(i=0;i<n;i++)
   {
    if(i==j||i==k) continue;
    if(a*(y[j]-y[i])==b*(x[j]-x[i]) ) num++;
   }
   if(max<num) max=num;
  }
 }
 cout<<max<<endl;
}
复杂度o(n^3)
方法2:
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1001;
int x[N];
int y[N];
float slope[N-1];
const float MaxSlope = 100000.0;
int n,i,j,deltax,deltay,t,cnt,halfn,u,v;
int MaxSame(int last)
{
 int ms = 0;
 int same = 0;
 int i = 1;
 while(i<last)
 {
  if(slope[i]==slope[i-1])
  {
   same++;
   if(same>ms)
    ms = same;
  }
  else
   same = 0;
  ++i;
 }
 return ms + 1;
}
int main()
{
 while(cin>>n)
 {
  for(i=0; i<n; ++i)
   cin>>x[i]>>y[i];
  halfn = n/2;
  cnt = 0;
  for(i=0; i<n; ++i)
  {
   //memset(slope,0,sizeof(slope));
   int index = 0;
   for(j=i+1; j<n; ++j)//第一次写的时候,是写的j从0开始,其实是多余的计算
   {
    //if(i==j)continue;
    deltax = x[i] - x[j];
    deltay = y[i] - y[j];
    if(deltax==0)
     slope[index++] = MaxSlope;
    else
     slope[index++] = float(deltay)/float(deltax);
   }
   sort(slope,slope+index);
   int t = MaxSame(index);
   if(cnt<t) cnt = t;
   if(cnt>halfn)
    break;
  }
  cout<<cnt+1<<endl;
  
 }
 return 0;
}
复杂度o(n^2logn),具体思路poj上有介绍。

67 1228 1399 15610 17311 190-100 1
原创粉丝点击