const double eps = 1e-8;
struct point{
	double x, y;
	point operator + (const point &p) const{return point{x + p.x, y + p.y};}
	point operator - (const point &p) const{return point{x - p.x, y - p.y};}
	point operator * (double t) const{return point{x * t, y * t};}
	point operator / (double t) const{return point{x / t, y / t};}
};
using vec = point;
double cross(point p1, point p2){return p1.x * p2.y - p1.y * p2.x;}  //叉乘
int sign(double k){
	if (k > eps) return 1;
	else if (k < -eps) return -1;
	else return 0;
}
int parallel(point p1, point p2, point p3, point p4){return sign(cross(p1 - p2, p3 - p4)) == 0;}  //平行
double dist(point p1, point p2){return sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));}  //两点间距离
point intersection(point p1, point p2, point p3, point p4){  //两直线交点
	double w1 = cross(p1 - p2, p4 - p2);
	double w2 = -cross(p1 - p2, p3 - p2);
	return (p3 * w1 + p4 * w2) / (w1 + w2);
}
bool onSegment(point p, point s, point t){return fabs(dist(p, s) + dist(p, t) - dist(s, t)) < eps;}  //点是否在线段上
double distPoint2Vector(point p1, vec v1, point p2, vec v2){return cross(v2, p2 - p1) / cross(v1, v2);}  //点 p1 到线段 v2 的距离
double intersectionPolygon(point A, point B){  //线段 AB 与多边形的公共长度
	vector<pair<double, int>> pos;
	vec v = B - A;
	for (int i = 0; i < n; i ++ ){
		int sign1 = sign(cross(v, poly[i] - A));
		int sign2 = sign(cross(v, poly[(i + 1) % n] - A));
		if (sign1 == sign2) continue;
		double w = distPoint2Vector(A, v, poly[i], poly[(i + 1) % n] - poly[i]);
		pos.push_back({w, sign1 - sign2});
	}
	sort(pos.begin(), pos.end());
	double res = 0;
	int sum = 0;
	for (int i = 0; i < pos.size(); i ++ ){
		sum += pos[i].second;
		if (sum){
			res += pos[i + 1].first - pos[i].first;
		}
	}
	return res * dist(A, B);
};
posted on 2022-11-15 15:20  Hamine  阅读(166)  评论(0编辑  收藏  举报