http://acm.cs.ecnu.edu.cn/problem.php?problemid=1019
题意:给n(4<=n<=50000)个点,它们之间没有重复的点,求出距离最远的一对点,输出它们距离的平方。
显然,最远点对一定在它们的凸包上。所以这个题目其实就是求凸包,然后枚举凸包上的所有点对,找出最远的。
WA~~找不出哪儿错了
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int MAXN=30005;
struct point
{
int x,y;
};
point list[MAXN];
int stack[MAXN],top;
int cross(point p0,point p1,point p2) //计算叉积 p0p1 X p0p2
{
return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}
double dis(point p1,point p2) //计算 p1p2的 距离
{
return sqrt((double)(p2.x-p1.x)*(p2.x-p1.x)+(p2.y-p1.y)*(p2.y-p1.y));
}
bool cmp(point p1,point p2) //极角排序函数 , 角度相同则距离小的在前面
{
int tmp=cross(list[0],p1,p2);
if(tmp>0) return true;
else if(tmp==0&&dis(list[0],p1)<dis(list[0],p2)) return true;
else return false;
}
void init(int n) //输入,并把 最左下方的点放在 list[0] 。并且进行极角排序
{
int i,k;
point p0;
scanf("%d%d",&list[0].x,&list[0].y);
p0.x=list[0].x;
p0.y=list[0].y;
k=0;
for(i=1;i<n;i++)
{
scanf("%d%d",&list[i].x,&list[i].y);
if( (p0.y>list[i].y) || ((p0.y==list[i].y)&&(p0.x>list[i].x)) )
{
p0.x=list[i].x;
p0.y=list[i].y;
k=i;
}
}
list[k]=list[0];
list[0]=p0;
sort(list+1,list+n,cmp);
}
void graham(int n)
{
int i;
if(n==1) {top=0;stack[0]=0;}
if(n==2)
{
top=1;
stack[0]=0;
stack[1]=1;
}
if(n>2)
{
for(i=0;i<=1;i++) stack[i]=i;
top=1;
for(i=2;i<n;i++)
{
while(top>0&&cross(list[stack[top-1]],list[stack[top]],list[i])<=0) top--;
top++;
stack[top]=i;
}
}
}
int main()
{
int n;
while(~scanf("%d", &n)){
init(n);
graham(n);
double len = 0.0;
for(int i = 0 ; i <= top ; i ++)
for(int j=i+1; j <= top; j++)
{
if( len < dis(list[stack[i]] , list[stack[j]]) )
len = dis(list[stack[i]] , list[stack[j]]);
}
printf("%.2f\n", len);
}
return 0;
}
贴一下安神神奇的代码:
枚举前三千,后三千AC
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
struct point{
double x,y;
};
bool cmp1(point a,point b){
return a.x < b.x;
}
bool cmp2(point a,point b){
return a.y < b.y;
}
point p[30005];
double dis(point a,point b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
for(int i = 0;i < n ;i ++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
double ans = 0.0;
sort(p,p+n,cmp1);
for(int i = 0;i < n && i < 3000;i ++){
for(int j = n-1;j >=0 && j >= n-3001; j--){
ans = max(ans,dis(p[i],p[j]));
}
}
sort(p,p+n,cmp2);
for(int i = 0;i < n && i < 3000;i ++){
for(int j = n-1;j >= 0 && j >= n-3001; j--){
ans = max(ans,dis(p[i],p[j]));
}
}
printf("%.2lf\n",ans);
}
return 0;
}