三分法~~~三分坐标不相等的那一维即可,3D的同理~~~再求两点间距离!附:菜鸟代码,貌似也得有点繁!
#include<stdio.h> #include<algorithm> #include<math.h> #define esp 1e-12 using namespace std; double a[2],b[2],c[2],d[2]; int t; double cal(double tem,int mark){ double x1,x2,y1,y2,temp[2]; if(mark==0){ x1=tem; y1=a[1]+(a[0]-x1)*(b[1]-a[1])/(a[0]-b[0]); temp[mark]=x1; } else if(mark==1){ y1=tem; x1=a[0]; temp[mark]=y1; }; x2=c[0]+(d[0]-c[0])*(a[mark]-temp[mark])/(a[mark]-b[mark]); y2=c[1]+(d[1]-c[1])*(a[mark]-temp[mark])/(a[mark]-b[mark]); return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } int main() { scanf("%d",&t); int flag,sum=1; while(t--){ scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&a[0],&a[1],&b[0],&b[1],&c[0],&c[1],&d[0],&d[1]); if(a[0]!=b[0]) flag=0; else if(a[0]==b[0]) flag=1; double l=min(a[flag],b[flag]),r=max(a[flag],b[flag]); while(r-l>esp){ double mid=(l+r)/2.0; double midmid=(r+mid)/2.0; if(cal(midmid,flag)-cal(mid,flag)>esp) r=midmid; else l=mid; } printf("Case %d: %.10f\n",sum++,cal(l,flag)); } return 0; }