题意:
求一个四边形的费马点。
分析:
模拟退火要么超时要么wa,这题的数据就是不想让随机算法过的。。其实四边形的费马点很简单,如果是凸四边形的话费马点是对角线交点,如果是凹四边形费马点是凹点。但题目给的四个点顺序是不确定的,所以要先求下凸包。
代码:
//poj 3990 //sep9 #include <iostream> #include <cmath> #include <algorithm> using namespace std; struct Point { double x,y,v; Point(){} Point(double x,double y):x(x),y(y){} }pnt[8],rec[8]; double getSum(Point p) { double sum=0; for(int i=0;i<4;++i) sum+=sqrt((p.x-pnt[i].x)*(p.x-pnt[i].x)+(p.y-pnt[i].y)*(p.y-pnt[i].y)); return sum; } int cmp(Point a,Point b) { if(a.y!=b.y) return a.y<b.y; return a.x<b.x; } int dbl(double x) { if(fabs(x)<1e-7) return 0; return x>0?1:-1; } 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 cross(Point a,Point b,Point c) { double x1=b.x-a.x; double y1=b.y-a.y; double x2=c.x-a.x; double y2=c.y-a.y; return dbl(x1*y2-x2*y1); } int graham() { int n=4; sort(pnt,pnt+n,cmp); rec[0]=pnt[0]; rec[1]=pnt[1]; int i,pos=1; for(i=2;i<n;++i){ while(pos>0&&cross(rec[pos-1],rec[pos],pnt[i])<=0) --pos; rec[++pos]=pnt[i]; } int bak=pos; for(i=n-1;i>=0;--i){ while(pos>bak&&cross(rec[pos-1],rec[pos],pnt[i])<=0) --pos; rec[++pos]=pnt[i]; } return pos; } int main() { int i; while(1){ for(i=0;i<4;++i) scanf("%lf%lf",&pnt[i].x,&pnt[i].y); double ans=0; if(pnt[0].x<-0.5) break; if(graham()==4){ ans+=dis(rec[0],rec[2]); ans+=dis(rec[1],rec[3]); } else{ ans=1e10; for(int i=0;i<4;++i) ans=min(ans,getSum(pnt[i])); } printf("%.4lf\n",ans+1e-8); } return 0; }
poj 3990 Fermat Point in Quadrangle 凸包和费马点
原文:http://blog.csdn.net/sepnine/article/details/44783621