hdu 1007 Quoit Design

题目是要求最近点对的距离,采用简单贪心:按x+y来排序,再一次遍历,求出相邻点对的最小距离。用G++一直TLE,实在是无语,看了discuss,有人说要用C++提交,结果用C++就直接AC了。另一位大牛用的暴力搜索,时间居然比我贪心还少,难以理解。

AC代码:

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<math.h>
#include<stdio.h>
using namespace std;
#define NUM 100005
struct point
{
	double x;
	double y;
}points[NUM];

bool cmp(point a, point b)
{

	return a.x+a.y < b.x+b.y;
}

double findDistance(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,i,j;
	double res,step;
	//freopen("C:\\Documents and Settings\\Administrator\\桌面\\input.txt","r",stdin);
	while(cin>>n&&n!=0){
		for(i=0;i<n;i++){
			cin>>points[i].x>>points[i].y;	
		}
		sort(points,points+n,cmp);
		res=1e10;
		for(i=1;i<n;i++){
			step=findDistance(points[i],points[i-1]);			
			if(step<res)
					res=step;			
		}
		printf("%.2lf\n",res/2); 		

	}
	return 0;

}



另一位大牛用的暴力搜索

#include<stdio.h>   
#include<string.h>   
#include<math.h>   
#include<algorithm>   
using namespace std;  
struct node  
{  
    double x,y;  
}g[100008];  
int cmp(node a,node b)  
{  
    if(a.x==b.x)  
        return a.y<b.y;  
    return a.x<b.x;  
}  
double DIS(node x,node y)  
{  
    return sqrt((x.x-y.x)*(x.x-y.x)+(x.y-y.y)*(x.y-y.y));     
}  
int main()  
{  
    int i,j,k,m,n;  
    double sum,dis;  
    while(scanf("%d",&m),m)  
    {  
        for(i=0;i<m;i++)  
            scanf("%lf%lf",&g[i].x,&g[i].y);  
        sort(g,g+m,cmp);  
        dis=1e10;  
        for(i=0;i<m;i++)  
        {  
            sum=1e10;  
            for(j=i+1;j<m;j++)  
            {  
                if(DIS(g[i],g[j])<sum)  
                    sum=DIS(g[i],g[j]);  
                else  
                    break;  
            }  
            if(sum<dis)  
                dis=sum;  
        }  
        printf("%.2lf\n",dis/2);  
    }  
    return 0;  
}  



你可能感兴趣的:(hdu 1007 Quoit Design)