点击打开题目链接
#include <cstdio> #include <cmath> #include <algorithm> #include <iostream> using namespace std; const double eps = 1e-10; struct Point //定义点 { double x, y; Point(double x = 0, double y = 0) : x(x), y(y) {} //构造函数,方便代码编写 }; const int MAXN = 300 + 10; Point P[MAXN], V[MAXN * MAXN]; typedef Point Vector; //向量是点的一个别名 //重载 +, -, *, <, == 运算符 Vector operator + (Vector A, Vector B) //“+”运算符,向量+向量=向量 { return Vector(A.x + B.x, A.y + B.y); } Vector operator - (Point A, Point B) //“-”运算符,点-点=向量 { return Vector(A.x - B.x, A.y - B.y); } Vector operator * (Vector A, double p) //“*”运算符,向量*数=向量 { return Vector(A.x * p, A.y * p); } bool operator < (const Point& a, const Point& b) //“<”运算符 { return a.x < b.x || (a.x == b.x && a.y > b.y); } //“三态函数”,减少精度问题 int dcmp(double x) { if (fabs(x) < eps) return 0; return x < 0 ? -1 : 1; } bool operator == (const Point& a, const Point& b) //“==”运算符 { return dcmp(a.x - b.x) == 0 && dcmp(a.y - b.y) == 0; } //点积 等于两向量长度的乘积再乘上它们夹角的余弦 double Dot(Vector A, Vector B) { return A.x * B.x + A.y * B.y; } //叉积,两向量组成的三角形的有向面积的两倍 double Cross(Vector A, Vector B) { return A.x * B.y - A.y * B.x; } //直线交点,调用前确保两条直线P+tv和Q+tw有唯一交点。当且仅当Cross(v,w)非0 Point GetLineIntersection(Point P, Vector v, Point Q, Vector w) { Vector u = P - Q; double t = Cross(w, u) / Cross(v, w); return P + v * t; } //判断线段是否相交,两线段恰好有一个公共点,且不在任意一条线段的端点 bool SegmentProperIntersection(Point a1, Point a2, Point b1, Point b2) { double c1 = Cross(a2 - a1, b1 - a1), c2 = Cross(a2 - a1, b2 - a1), c3 = Cross(b2 - b1, a1 - b1), c4 = Cross(b2 - b1, a2 - b1); return dcmp(c1) * dcmp(c2) < 0 && dcmp(c3) * dcmp(c4) < 0; } //判断一个点是否在一条线段上(不包含端点) bool OnSegment(Point p, Point a1, Point a2) { return dcmp(Cross(a1 - p, a2 - p)) == 0 && dcmp(Dot(a1 - p, a2 - p)) < 0; } int main() { int n, kcas = 0; while (~scanf("%d", &n), n) { for (int i = 0 ; i < n; i++) { scanf("%lf%lf", &P[i].x, &P[i].y); V[i] = P[i]; } n--; int numOfPoint = n, numOfEdge = n; for (int i = 0; i < n; i++) //找出所有线段相交形成的新增点 for (int j = i + 1; j < n; j++) if (SegmentProperIntersection(P[i], P[i + 1], P[j], P[j + 1])) V[numOfPoint++] = GetLineIntersection(P[i], P[i + 1] - P[i], P[j], P[j + 1] - P[j]); sort(V, V + numOfPoint); //排序 numOfPoint = unique(V, V + numOfPoint) - V; //删除重复的点 for (int i = 0; i < numOfPoint; i++) for (int j = 0; j < n; j++) if (OnSegment(V[i], P[j], P[j + 1])) numOfEdge++; printf("Case %d: There are %d pieces.\n", ++kcas, numOfEdge + 2 - numOfPoint); } return 0; }