int segmentsIntersection (complex<T> p1,complex<T> p2,complex<T> p3,complex<T> p4,complex<double>& inter) { if(sigcross(p3-p1,p2-p1)*sigcross(p2-p1,p4-p1)<0)return 0; if(sigcross(p1-p3,p4-p3)*sigcross(p4-p3,p2-p3)<0)return 0; if(sigcross(p2-p1,p3-p1)==0&&sigcross(p2-p1,p4-p1)==0) { if(p1.x()==p2.x()) { if(p1.y()>p2.y())swap(p1,p2); if(p3.y()>p4.y())swap(p3,p4); int ly=max(p1.y(),p3.y()); int hy=min(p2.y(),p4.y()); if(ly>hy)return 0; if(ly<hy)return 2; inter=p2; return 1; } else { if(p1.x()>p2.x())swap(p1,p2); if(p3.x()>p4.x())swap(p3,p4); int lx=max(p1.x(),p3.x()); int hx=min(p2.x(),p4.x()); if(lx>hx)return 0; if(lx<hx)return 2; inter=p2; return 1; } } linesIntersection(p1,p2,p3,p4,inter); return 1; }
bool linesIntersection (complex<T> p1,complex<T> p2,complex<T> p3, complex<T> p4,complex<double>& p) { if(fabs(dcross(p1-p2,p3-p4))<EPS)return false; double t=dcross(p3-p1,p3-p4)/dcross(p2-p1,p3-p4); p.x()=1.0*p1.x()+1.0*(p2.x()-p1.x())*t; p.y()=1.0*p1.y()+1.0*(p2.y()-p1.y())*t; return true; }
bool circlesIntersection ( complex<T> p1,T r1,complex<T> p2,T r2,complex<double>& inter) { double dx = p2.x() - p1.x(); double dy = p2.y() - p1.y(); double d = mysqrt(dx*dx + dy*dy); if(d>r1+r2+EPS||d+EPS<fabs(r1-r2))return false; //circle overlap if(d<EPS)return false; double e = (r1*r1 - r2*r2 + d*d)/(2*d); double f = mysqrt(r1*r1 - e*e); inter=complex<double>(1.0*p1.x() + (e*dx - f*dy)/d,1.0*p1.y() + (f*dx + e*dy)/d); return true; }
double length(complex<T> p) { return sqrt(1.0*p.x()*p.x()+1.0*p.y()*p.y()); }
double dcross(complex<T> p1,complex<T> p2) { return 1.0*p1.x()*p2.y()-p2.x()*p1.y(); }
llint llcross(complex<T> p1,complex<T> p2) { return (llint)p1.x()*(llint)p2.y()-(llint)p2.x()*(llint)p1.y(); }