题意:平面上有一个包含n个端点的一笔画,第n个端点总是和第一个端点重合,因此团史一条闭合曲线。组成一笔画的线段可以相交,但是不会部分重叠。求这些线段将平面分成多少部分(包括封闭区域和无限大区域)。
分析:若是直接找出所有区域,或非常麻烦,而且容易出错。但用欧拉定理可以将问题进行转化,使解法变容易。
欧拉定理:设平面图的顶点数、边数和面数分别为V,E,F,则V+F-E=2。
这样,只需求出顶点数V和边数E,就可以求出F=E+2-V。
设平面图的结点由两部分组成,即原来的结点和新增的结点。由于可能出现三线共点,需要删除重复的点。
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<memory.h>
#include<cstdlib>
#include<vector>
#define clc(a,b) memset(a,b,sizeof(a))
#define LL long long int
using namespace std;
const int inf=0x3f3f3f3f;
const double eps = 1e-;
const int N = + ; struct Point
{
double x, y;
Point(double x = , double y = ) : x(x), y(y) { }
}; 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);
} 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 ;
else
return x < ? - : ;
} bool operator == (const Point& a, const Point& b)
{
return dcmp(a.x - b.x) == && dcmp(a.y - b.y) == ;
} 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;
} 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) < && dcmp(c3) * dcmp(c4) < ;
} bool OnSegment(Point p, Point a1, Point a2)
{
return dcmp(Cross(a1-p, a2-p)) == && dcmp(Dot(a1-p, a2-p)) < ;
} Point P[N], V[N*N]; int main()
{
int n, cas = ;
while(~scanf("%d",&n) && n)
{
for(int i = ; i < n; i++)
{
scanf("%lf%lf", &P[i].x, &P[i].y);
V[i] = P[i];
}
n--;
int vcnt = n, ecnt = n;
for(int i = ; i < n; i++)
for(int j = i + ; j < n; j++)
{
if(SegmentProperIntersection(P[i], P[i+], P[j], P[j+]))
V[vcnt++] = GetLineIntersection(P[i], P[i+]-P[i], P[j], P[j+]-P[j]);
}
sort(V, V+vcnt);
vcnt = unique(V, V+vcnt) - V;//去掉相邻元素中重复的,使用前先排序
for(int i = ; i < vcnt; i++)
for(int j = ; j < n; j++)
if(OnSegment(V[i], P[j], P[j+]))
ecnt++;
int ans = ecnt + - vcnt;
printf("Case %d: There are %d pieces.\n", ++cas, ans);
}
return ;
}